一、设置请求的编码
第一种方法:
在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");
二、获取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字符编码