3个地方设置编码,解决乱码问题
public static String GetResponse(HttpMethodBase Method) throws IOException {
String charset= Method.getResponseCharSet();
System.out.println("返回的字符编码为:"+charset);
InputStream responseBody = Method.getResponseBodyAsStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(responseBody));
BufferedReader br = new BufferedReader(new InputStreamReader(Method.getResponseBodyAsStream(), "ISO-8859-1"));//1
String tempbf;
StringBuffer htmlbf = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
// htmlbf.append(tempbf);
htmlbf.append(new String(tempbf.getBytes("iso-8859-1"),"utf-8"));//2
htmlbf.append("/n");
}
return htmlbf.toString();
}//end GetResponse
然后在构建GetMethod或PostMethod时也指定编码
Method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//3
或者 NameValuePair p2 = new NameValuePair( "Content-Type","text/html; charset=utf-8");
post.setRequestBody( new NameValuePair[]{p2})//3
本文介绍了解决HTTP请求中中文乱码的方法,通过在三个关键位置设置合适的字符编码(如ISO-8859-1转UTF-8),确保了从服务器获取的数据能正确显示中文内容。
1014

被折叠的 条评论
为什么被折叠?



