【问题标题】:Send UTF-8 chars via HttpURLConnection failing通过 HttpURLConnection 发送 UTF-8 字符失败
【发布时间】:2013-04-07 17:38:40
【问题描述】:

我已经花了半个星期天的时间,现在我需要帮助:

我想使用 Java HttpURLConnection 向服务器发送一个包含特殊字符 UTF-8 编码的字符串。字符的正确编码失败。

例子:

strToSend:äù€ strUrlEncoded: %C3%A4+%C3%B9+%E2%82%AC strReceived:ä ù â¬

我的代码:

        urlConnection = (HttpURLConnection) new URL("http://localhost:8080/NetworkingServer/ServerServlet").openConnection();
        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true); // Triggers POST.
        urlConnection.setRequestProperty("accept-charset", "UTF-8");
        urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");

        String strToSend = "ä ù €";
        System.out.println("strToSend: " + strToSend);
        String strUrlEncoded = URLEncoder.encode(strToSend, "UTF-8");
        System.out.println("strUrlEncoded: " + strUrlEncoded);

        OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
        writer.write(String.format("content=%s", strUrlEncoded));
        writer.close();

有什么想法吗?

【问题讨论】:

    标签: java utf-8 httpurlconnection


    【解决方案1】:

    您需要在 Content-Type 标头中设置编码。

    将其设置为“application/x-www-form-urlencoded; charset=utf-8”。目前您只设置accept-charset - 这告诉服务器要发回什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多