HttpClient handling Chinese garbled characters

Source: Internet
Author: User

The problem of Chinese garbled HttpClient request
Related class libraries:
Commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar

--passing parameters to the request

HttpClient client = new HttpClient ();

HttpMethod method= new Postmethod (URL);

Httpmethodparams params = new Httpmethodparams ();

Params.setcontentcharset ("GB2312");

Method.setparams (params);

Way One:
The simplest way to output the page directly, here basically does not need any settings.

System.out.println (Getmethod.getresponsebodyasstring ());

Way two:
Read using stream mode

InputStream in = Getmethod.getresponsebodyasstream ();

The coding rules here should correspond to the above

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

Way three:
Of course, you can also use this way, because the default is to use Iso-8859-1, nothing more than a few times the transcoding

InputStream in = Getmethod.getresponsebodyasstream ();

Here use 8859-1 read

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

}

Turn 8859-1 into GB2312 again

System.out.println (New String (Html.tostring (). GetBytes ("Iso-8859-1"), "GB2312"));


I still recommend using the first method, but I think it's essentially the same
The request section can also be set in several ways:

Getmethod.getparams (). Setparameter (Httpmethodparams.http_content_charset, "GB2312");

Getmethod.addrequestheader ("Content-type", "text/html; charset=gb2312 ");

Transferred from: http://871421448.iteye.com/blog/1546950

HttpClient handling Chinese garbled characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.