HttpURLConnection请求返回数据部分乱码问题

问题:返回数据部分中文乱码,当中文字数为偶数时,不出现乱码;中文字数为奇数时,最后一位中文是以“??结尾

解决方案:发送post请求的接口已设置filer:encoding=UTF-8,且工作空间字符集设置为UTF-8。


服务接口返回内容是以UTF-8格式发送的,接收时怎么会出现GBK格式?
继续深究,发现HttpURLConnection 接收返回内容时没有设置字符集,此时使用默认字符集GBK,即

BufferedReader bfReader= new BufferedReader(new InputStreamReader(conn.getInputStream())),

为默认字符集接收。

继续执行到 lines = new String(lines.getBytes(), "UTF-8")这一行,便出现了奇偶数部分乱码的情况。


public static String sendPostNew(String url, String param,String authorization) {
String result = "";
try {
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl
.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.addRequestProperty("Authorization", "Bearer " + authorization);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

PrintWriter out = new PrintWriter(new OutputStreamWriter(
httpConn.getOutputStream(), "utf-8"));

out.print(param);
out.flush();
out.close();


int code=httpConn.getResponseCode();

if (code==200) {

                                //关键在这行代码。

BufferedReader in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close(); 
}else{ 
result=code+"";  
}
} catch (Exception e) {
System.out.println("没有结果!" + e);
}
return result;

}


http://blog.csdn.net/yss19900512/article/details/49335813

你可能感兴趣的:(HttpURLConnection请求返回数据部分乱码问题)