Landlord before the time to do Android projects, using HTTP communication, so the landlord in line with practiced hand attitude, his own writing httpurlconnection communication process, and then in the test, found that the use of post requests have been garbled, this time the landlord began to look at the data sent, found that the data sent is correct, no garbled, is utf-8, and then look at the server code, yes, also carried out the operation of transcoding, then, what is the problem? This troubled the landlord for a long time, later, the landlord inadvertently found that the book (the first line of code) for communication, the POST request data using the following code:
AD (New Runnable () {@Override public void run () {httpurlconnection connection = null ; try {URL url = new URL (address); Connection = (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("POST"); Connection.setdooutput (TRUE); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); DataOutputStream out = new DataOutputStream (Connection.getoutputstream ()); Out.write (Data.getbytes ()); InputStream in = Connection.getinputstream (); BufferedReader reader = new BufferedReader (new InputStreamReader (in)); StringBuilder response = new StringBuilder (); String Line; while ((Line=reader.readline ())!=null) {response.append (line); }
However, the landlord in the use of Out.write (Data.getbytes ()), written out.writebytes (data). Can be said to be very small a difference, then when the landlord will this line of code after the test, found garbled problem solved, and then the landlord on the blindfolded, what ghosts, there are two functions have a difference??? Later, the landlord consulted the data, found that the two functions are really very big difference.
The former converts the data (string type) to a byte array and then transmits it. There is no problem with this. How does the latter change, and look at its source code:
At this time the problem arose, see s.length (); for Chinese, get length is the length of the word, the following is the verification:
、
We all know that the storage of Chinese characters are two bytes, but the length of the acquisition is 3, so it is necessary to make a strong turn to intercept a portion of the data, so garbled, the following is the experiment:
HttpURLConnection post garbled on Android HTTP communication