Reputation: 101
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.
Upvotes: 10
Views: 21627
Reputation: 1223
I had the same problem. You should use this code:
httpPost.setEntity(new StringEntity(json, "UTF-8"));
Hope this can help you.
Upvotes: 25
Reputation: 41
I'd suggest you try the addRequestHeader method of the HttpPost instead like
httpPost.addRequestHeader("Content-Type", "text/plain;charset=UTF-8");
as that is the recommended way of adding content type header to your request.
Upvotes: 0
Reputation: 28951
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.
Upvotes: 1