HttpClient 流式读取时中文乱码的解决方法
1、非流式读取HttpClient中可以之间使用HttpMethod的getResponseBodyAsString()方法获取返回的内容,在读取之前,如果需要做编码设置可以这样:
HttpMethod get=new GetMethod(url);
httpClient.executeMethod(get);
get.getParams().setContentCharset("GBK");
这么做虽然可以解决中文乱码问题,但是在HttpClient 3.1中这种方法是不推荐的,会发出警告。
2、流式读取
HttpClient推荐使用流式的读取返回内容,如下:
BufferedReader reader=new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
String tmp=null;
String htmlRet="";
while((tmp=reader.readLine())!=null){
htmlRet+=tmp+"\r\n";
}
System.out.println(new String(htmlRet.getBytes(),"GB2312"));
但是经过尝试发现这样会出现中文乱码问题。经过N次实验后,将上面代码修改如下,乱码问题随之解决。
HttpClient httpClient=new HttpClient();
HttpMethod get=new GetMethod(send_url);
try {
httpClient.executeMethod(get);
//System.out.println(get.getResponseBodyAsString());
BufferedReader reader=new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),"ISO-8859-1"));
String tmp=null;
String htmlRet="";
while((tmp=reader.readLine())!=null){
htmlRet+=tmp+"\r\n";
}
System.out.println(new String(htmlRet.getBytes("ISO-8859-1"),"GB2312"));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
get.releaseConnection();
}
最后更新:2017-04-03 20:19:52
上一篇:
静态局部变量
下一篇:
Mybatis中传参包There is no getter for property named 'XXX' in 'class java.lang.String'
LinearLayout按下(pressed)或获取焦点(focused)时背景设置不同颜色或图片
Linux平台多线程下的计时
因为有你,我不孤单
构建VPN满足云下开发环境访问云HBase数据库
Android开发7——android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1
常见的java基础面试题汇总-01
《Vim实用技巧(第2版)》——2.4 用次数做简单的算术运算
那些只知其产品而不知其人的创始人们
C++编程规范之1:在高警告级别干净利落地进行编译
恢复Hyper-V虚拟机丢失的数据文件过程