UTF-8 encoding issue with servlet and apache HttpClient

I have a servlet that sends a utf-8 encoded string. I also have a client written using the apache httpcomponents library.

My problem is reading the response in utf-8. Some special characters, such as ñ or ç, are not read correctly. If I test the server with the html page sending the request, the string is correct and UTF-8 encoding without specification.

Some snippets: Servlet

response.setContentType ("application/json; charset=UTF-8");
PrintWriter out = response.getWriter ();
out.write (string);

Client

entity = response.getEntity ();
entity.getContentEncoding (); //returns null
resultado = EntityUtils.toString (entity, HTTP.UTF_8); //Some characters are wrong

Has anyone had the same problem?

SOLVE: Sorry that the client and server are working correctly. I am writing an Android application and it seems that logcat (where I print messages) does not support utf-8 encoding.

+3
4

response.setCharacterEncoding("utf-8");

setContentType? , ...

, , response.getWriter() , , .

+7

, UTF-8:

out.write((yourstring.getBytes("UTF-8"));
+4

StandardCharsets.UTF_8 can be used with EntityUtil to get the correct encoding.

Here is an example snippet:

HttpEntity entity = response.getEntity();
String webpage = EntityUtils.toString(entity, StandardCharsets.UTF_8);
+2
source

I have a similar problem that I solved with UTF-8 encoding as follows:

IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8)

namespace:

import com.google.common.base.Charsets;
0
source

Source: https://habr.com/ru/post/1780305/


All Articles