HttpClient 處理中文亂碼

來源:互聯網
上載者:User

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");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.