java - Servlet 的 UTF-8 响应

标签 java servlets utf-8

我正在从 Servlet 中的 Perl 页面读取 HTTP 响应,如下所示:

public String getHTML(String urlToRead) {
        URL url;
        HttpURLConnection conn;
        BufferedReader rd;
        String line;
        String result = "";
        try {
           url = new URL(urlToRead);
           conn = (HttpURLConnection) url.openConnection();
           conn.setRequestMethod("GET");
           conn.setRequestProperty("Accept-Charset", "UTF-8");
           conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");

           rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
           while ((line = rd.readLine()) != null) {
              byte [] b = line.getBytes();
              result += new String(b, "UTF-8");
           }
           rd.close();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return result;
   }

我使用以下代码显示此结果:

response.setContentType("text/plain; charset=UTF-8");

        PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"), true);


        try {

            String query = request.getParameter("query");
            String type = request.getParameter("type");

            String res = getHTML(url);
            out.write(res);

        } finally {            
            out.close();
        }

但是响应仍然没有编码为 UTF-8。我做错了什么?

提前致谢。

最佳答案

line.getBytes() 的调用看起来很可疑。如果您确定返回的内容是 UTF-8 编码的,您可能应该将其设为 line.getBytes("UTF-8")。此外,我不确定为什么有必要。从 BufferedReader 中获取数据的典型方法是使用 StringBuilder 继续附加从 readLine 检索到的每个 String > 成结果。 Stringbyte[] 之间的来回转换是不必要的。

result 更改为 StringBuilder 并执行以下操作:

while ((line = rd.readLine()) != null) {
    result.append(line);
}

关于java - Servlet 的 UTF-8 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868314/

相关文章:

jsp - 部署tomcat 7.0 404错误

asp.net-mvc - 如何在 C# 中使用带有 BOM 的 UTF8 编码 GetBytes()?

java - 如何读取和排序仅由空格分隔的数据?

java - 使用 HttpSession 时,变量无法从一个 JSP 转移到另一个 JSP

java - "AWT-EventQueue-0"java.lang 中的 NullPointerException

java - 如何在java中访问或显示ftp服务器上可用的文件列表

java - 在哪里 setCharSet() 以在 JPanel 上显示 UTF-8 文件中的字符串

javascript - 从JavaScript向C++发送数据,超过127的字节值被替换为 "replacement character"

java - 如何按升序设置数字(示例 : 0, 1, 2, 4, 6 至 0, 1, 2, 3, 4)

java - 表单和实体类的用法