UTF-8 code (garbled) problem solving method for Android post data _android

Source: Internet
Author: User
Tags tojson

A bug was encountered today: a piece of data that was posted to the server by the client caused an unknown exception on the server side. The server side confirmation is a coded conversion error. This intercepts the network packet for analysis and discovers that the JSON data in the client post contains the following paragraph (hex form):

Copy Code code as follows:
... B7 20 52 69 63 ...

The problem is on this b7. Looking at the Unicode code table, U+00B7 is Middle DOT and its UTF-8 representation should be C2 B7, but why does it become B7 in the data sent by the client?

Because the system used Ormlite, Gson and async-http several libraries, so the investigation. Finally found that the original is to send data to the server did not specify the text encoding, causing async-http (the actual Apache common HTTP client) to send the data in iso-8559-1 format, U+00B7 is encoded into B7, The server then attempted to use UTF-8 to decode with an error.

The code snippet for the error is as follows:

Copy Code code as follows:

Gson Gson = new Gson ();
String JSON = Gson.tojson (data);
stringentity entity = new stringentity (JSON);
Httpclient.post (context, URL, entity, "Application/json", New Texthttpresponsehandler () ...);

The third line, New Stringentity (JSON), did not specify an encoding to cause an error. The following corrections are followed:
Copy Code code as follows:

Gson Gson = new Gson ();
String JSON = Gson.tojson (data);
stringentity entity = new Stringentity (JSON, "utf-8");
Httpclient.post (context, URL, entity, "Application/json;charset=utf-8", New Texthttpresponsehandler () ...);

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.