servlet 和 apache HttpClient 的 UTF-8 编码问题
我有一个 servlet,它发送一个 utf-8 编码的字符串。我还有一个用 apache httpcomponents 库编写的客户端。
我的问题是读取 utf-8 格式的响应。某些特殊字符(如 ñ 或 ç)无法正确读取。如果我用发送请求的html页面测试服务器,字符串是正确的,并且编码是UTF-8无BOM。
一些片段: Servlet
response.setContentType ("application/json; charset=UTF-8");
PrintWriter out = response.getWriter ();
out.write (string);
客户端
entity = response.getEntity ();
entity.getContentEncoding (); //returns null
resultado = EntityUtils.toString (entity, HTTP.UTF_8); //Some characters are wrong
有人遇到过同样的问题吗?
已解决: 抱歉,客户端和服务器工作正常。我正在编写一个 Android 应用程序,似乎 logcat (我打印消息的地方)不支持 utf-8 编码。
I have a servlet that sends a string with utf-8 encoding. Also I have a client written with apache httpcomponents library.
My problem is reading the response in utf-8. Some special characters like ñ or ç are not read correctly. If I test the server with an html page sending a request, the string is correct and the encoding is UTF-8 without BOM.
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?
SOLVED:
Sorry guys the client and server were working correctly. I'm writting an android app and it seems that the logcat (where I print the messages) doesn't support utf-8 encoding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否尝试
过通过
setContentType
设置编码?根据文档,它应该没有什么区别,但谁知道呢...另外,请确保在设置字符编码之前没有在代码中的任何位置调用
response.getWriter()
,因为在这种情况下,后者不会产生任何影响。Have you tried
instead of setting the encoding via
setContentType
? It shouldn't make a difference according to the documentation, but who knows...Also, make sure you didn't call
response.getWriter()
anywhere in your code before setting the character encoding, because the latter would not have any effect in that case.确保流字节采用 UTF-8 格式:
Make sure stream bytes are in UTF-8 format:
StandardCharsets.UTF_8 可以与 EntityUtil 一起使用以获得正确的编码。
这是一个示例片段:
StandardCharsets.UTF_8 can be used with EntityUtil to get the proper encoding.
Here is a sample snippet:
我有一个类似的问题,我通过使用 UTF-8 编码解决,如下所示:
命名空间:
I've got a similar problem that i solved by using UTF-8 encoding as following:
Namespace: