当我们在程序中访问远程服务器的接口时,有时会遇到中文乱码的问题,这里提供一种解决方案。
这里使用InputStreamReader 和BufferedReader
/**
* 从xx系统拉取用户信息
* @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;
}