HttpClient 請求的中文亂碼問題
相關類庫:
commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar
--給請求傳遞參數
HttpClient client = new HttpClient();
HttpMethod method= new PostMethod(url);
HttpMethodParams params = new HttpMethodParams();
params.setContentCharset("GB2312");
method.setParams(params);
方式一:
最簡單的方式,直接輸出頁面,這里基本上不需要任何設置。
System.out.println(getMethod.getResponseBodyAsString());
方式二:
使用流方式讀取
InputStream in = getMethod.getResponseBodyAsStream();
//這里的編碼規則要與上面的相對應
BufferedReader br = new BufferedReader(new InputStreamReader(in,"GB2312"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
html.append(tempbf +"\n");
}
System.out.println(html.toString());
方式三:
當然還可以使用這樣的方式,因為默認是使用ISO-8859-1,無非就是多進行了幾次轉碼
InputStream in = getMethod.getResponseBodyAsStream();
//這里使用8859-1讀取
BufferedReader br = new BufferedReader(new InputStreamReader(in,"ISO-8859-1"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
html.append(tempbf +"\n");
}
//將8859-1再次轉成GB2312
System.out.println(new String(html.toString().getBytes("ISO-8859-1"),"GB2312"));
我還是建議使用第一種方法,但我認為本質上是一致的
對於請求部分還可以通過如下幾種方式進行設置
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GB2312");
getMethod.addRequestHeader("Content-Type", "text/html; charset=gb2312");
轉自:http://871421448.iteye.com/blog/1546950
