HttpPost UTF-8 encoding / decoding Java

I am having problems trying to send utf8 formatted post data from client to my server.

I've read a lot about this topic, but I can't seem to find a solution. I'm sure I'm missing something basic.

Here is my client code to make a 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 on my server side to get the text in utf8 (Polish characters don't appear, I get "?" 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 only wrote the relevant code.

Any help in this regard would be appreciated. Thank.

+3


source to share


3 answers


I had the same problem. You should use this code:

httpPost.setEntity(new StringEntity(json, "UTF-8"));

      



Hope this helps you.

+3


source


As I see it you should be using new StringEntity(data, ContentType.APPLICATION_JSON)

. By default, this iso-8859-1

is setHeader

not the correct way to set the encoding as I understand it.



+1


source


I suggest you try the addRequestHeader method for the HttpPost rather than

httpPost.addRequestHeader("Content-Type", "text/plain;charset=UTF-8");

      

as this is the recommended way to add a content type header to your request.

0


source







All Articles