HttpClient 處理中文亂碼

HttpClient 請求的中文亂碼問題 
相關類庫: 
commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar html

--給請求傳遞參數app

HttpClient client = new HttpClient();編碼

HttpMethod method= new PostMethod(url);url

HttpMethodParams params = new HttpMethodParams();code

params.setContentCharset("GB2312");htm

method.setParams(params);blog

 

方式一:
最簡單的方式,直接輸出頁面,這裏基本上不須要任何設置。get

System.out.println(getMethod.getResponseBodyAsString());it

 

方式二:
使用流方式讀取class

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

相關文章
相關標籤/搜索