【问题标题】:UTF-8 encoding problem with servlet and apache HttpClientservlet 和 apache HttpClient 的 UTF-8 编码问题
【发布时间】:2011-05-25 14:14:27
【问题描述】:

我有一个 servlet,它发送一个带有 utf-8 编码的字符串。我也有一个用 apache httpcomponents 库编写的客户端。

我的问题是阅读 utf-8 格式的响应。某些特殊字符(如 ñ 或 ç)无法正确读取。如果我用发送请求的 html 页面测试服务器,字符串是正确的,编码是 UTF-8,没有 BOM。

一些sn-ps: 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 编码。

【问题讨论】:

    标签: java apache servlets utf-8 httpclient


    【解决方案1】:

    你试过了吗

    response.setCharacterEncoding("utf-8");
    

    而不是通过setContentType 设置编码?根据文档,它不应该有所作为,但谁知道......

    另外,请确保在设置字符编码之前没有在代码中的任何位置调用 response.getWriter(),因为在这种情况下后者不会有任何影响。

    【讨论】:

    • 你能确定问题出在 servlet 端还是客户端?
    • 是的,您应该使用 Wireshark 之类的工具进行检查。
    • 我还测试了与wireshark的连接,我发现特殊字符发送不正确,但firefox显示正确:S。使用 setCharacterEncoding 和 text/plain content-type 测试,但仍然失败。
    • 你是对的,在使用字符集信息设置 contentType 之后添加或不添加 response.setCharacterEncoding("utf-8") 没有任何区别。但是当我改变调用 response.getWriter() 的位置时,它立刻就完美了。非常感谢。
    【解决方案2】:

    确保流字节为 UTF-8 格式:

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

    【讨论】:

      【解决方案3】:

      StandardCharsets.UTF_8 可以与 EntityUtil 一起使用以获得正确的编码。

      这是一个示例 sn-p:

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

      【讨论】:

        【解决方案4】:

        我有一个类似的问题,我通过使用 UTF-8 编码解决了如下问题:

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

        命名空间:

        import com.google.common.base.Charsets;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-09
          • 1970-01-01
          • 2010-12-01
          • 1970-01-01
          • 2013-03-26
          相关资源
          最近更新 更多