HttpClient4.x编码

一、设置请求的编码

第一种方法:

在Hedaer中设置Content-Type

HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");

第二种方法:

设置HttpClient的CONTENT_CHARSET

HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

第三种方法:

设置get/post method的CONTENT_CHARSET

HttpGet httpGet = new HttpGet(url);
httpGet.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");


这三种设置方法的优先级依次递增,也就是说如果同时设置,则以后面的为准。如果都没有设置,默认charset是ISO-8859-1。


二、获取response的编码:

HttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));


三、获取response内容:

HttpEntity httpEntity =response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
String line;
while((line = br.readLine()) != null){
	System.out.println(line);
	System.out.println("\n");
}


也可在获得response后转码:

HttpEntity httpEntity =response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line;
while((line = br.readLine()) != null){
	System.out.println(new String(line.getBytes("ISO-8859-1"),"UTF-8"));
	System.out.println("\n");
}	





参考:httpclient4 中文版帮助文档,最新官方版翻译版(第一章 下)

httpclient编码

HttpClient字符编码

你可能感兴趣的:(HttpClient4.x编码)