當(dāng)我們在程序中訪問遠(yuǎn)程服務(wù)器的接口時,有時會遇到中文亂碼的問題,這里提供一種解決方案彻况。
這里使用InputStreamReader 和BufferedReader
/**
* 從xx系統(tǒng)拉取用戶信息
* @param userAccount
* @return
*/
public static String getUserInfo(String userAccount,String pathType) {
String[] serverInfo = getServerInfo(getUserInfo);
String serverPath = composeServerPath(serverInfo,userAccount,pathType);
String result = "";
HttpURLConnection connection = null;
try {
URL url = new URL(serverPath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("contentType", "utf-8");
connection.setRequestProperty("Accept-Charset", "utf-8");
if (connection.getResponseCode() != 200) {
log.error("連接失敗!");
} else {
InputStreamReader in = null;
in = new InputStreamReader(connection.getInputStream(),"utf-8");
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
result = stringBuffer.toString();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (connection != null)
connection.disconnect();
}
return result;
}