Java httpurlconnection Simulation Request rest interface to solve Chinese garbled problem

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/hwj3747/article/details/53635539

When Java uses HttpURLConnection to request the rest interface, there is a problem that the POST request is garbled in Chinese, and the incoming string can be encoded by many methods, which is as follows:

String testring=New string ("Hello". GetBytes ("Iso-8859-1"), "UTF-8");

The requests for online httpurlconnection are usually the same:

 Public Staticstring postrequest (string url,string obj) {string jsonstring=""; Try {             //Create a connectionURL url =Newurl (URL); HttpURLConnection Connection=(httpurlconnection) URL. OpenConnection (); Connection.setdooutput (true); Connection.setdoinput (true); Connection.setrequestmethod ("POST");//Set Request MethodConnection.setrequestproperty ("Charsert", "UTF-8");//Set Request EncodingConnection.setusecaches (false); Connection.setinstancefollowredirects (true); Connection.setrequestproperty ("Content-type",                     "Application/json");             Connection.connect (); //POST RequestDataOutputStream out =NewDataOutputStream (Connection.getoutputstream ());//a critical stepout.writebytes (obj);             Out.flush ();             Out.close (); //Read Response            if(Connection.getresponsecode () ==200) {BufferedReader reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));                String lines; StringBuffer SB=NewStringBuffer ("");  while((lines = Reader.readline ())! =NULL) {lines=NewString (Lines.getbytes (), "Utf-8");                Sb.append (lines); } jsonstring=sb.tostring ();            Reader.close (); }//a return value of 200 outputs the correct response information            if(Connection.getresponsecode () ==400) {BufferedReader reader=NewBufferedReader (NewInputStreamReader (Connection.geterrorstream ()));                String lines; StringBuffer SB=NewStringBuffer ("");  while((lines = Reader.readline ())! =NULL) {lines=NewString (Lines.getbytes (), "Utf-8");                Sb.append (lines); } jsonstring=sb.tostring ();            Reader.close (); }//return value error, output error return information//Disconnect ConnectionConnection.disconnect (); } Catch(malformedurlexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }         returnjsonstring; } 

It is important to note that when the return value is 200, Connection.getinputstream () has a value, Connection.getinputstream () is empty when the return value is 400, Connection.geterrorstream () has a value.

The above is the most online blog article writing, but I used this method encountered the problem of Chinese garbled. In Out.writebytes (obj), this step, regardless of how the string is converted to obj, the result is garbled, the final solution is this:
Put this part of the code,

New DataOutputStream (                     // critical step )            

Change into

New PrintWriter (new OutputStreamWriter (Connection.getoutputstream (), "Utf-8"));              Out.println (obj);

Solve.

Java httpurlconnection Simulation Request rest interface to solve Chinese garbled problem

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.