I am having troubles trying to send post data in utf8 format from the client to my server.
I have read a lot about this topic but I can´t find the solution. I am sure that I am missing something basic.
Here is my client code to make the post request
public static PostResponse post(String url, String data) {
PostResponse response = new PostResponse();
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/plain; charset=UTF-8");
// 3. set string to StringEntity
StringEntity se = new StringEntity(data);
// 4. set httpPost Entity
httpPost.setEntity(se);
// 5. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
} catch (IOException e) {
}
return response;
}
This is the code in my server side to receive the text in utf8 (Polish characters are not appearing, I am getting "?" instead.)
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
BufferedReader reader;
reader = req.getReader();
Gson gson = new Gson();
msg = gson.fromJson(reader, MsgChat.class); //String in the client was json
} catch (IOException e) {
}
}
I wrote only the relevant code.
I would appreciate any help regarding this. Thanks.
Introduction. When working with Strings in Java, we oftentimes need to encode them to a specific charset, such as UTF-8. UTF-8 represents a variable-width character encoding that uses between one and four eight-bit bytes to represent all valid Unicode code points.
String objects in Java are encoded in UTF-16. Java Platform is required to support other character encodings or charsets such as US-ASCII, ISO-8859-1, and UTF-8. Errors may occur when converting between differently coded character data.
The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units (that is, sequences of chars) and sequences of bytes.
The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.
I had the same problem. You should use this code:
httpPost.setEntity(new StringEntity(json, "UTF-8"));
Hope this can help you.
As I see you should use new StringEntity(data, ContentType.APPLICATION_JSON)
. By default it is iso-8859-1
, setHeader
is not correct way to set encoding as I understand it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With