通过HttpURLConnection发送UTF-8字符失败

时间:2013-04-07 17:38:41

标签: java utf-8 httpurlconnection

我已经花了一半星期天,我现在需要帮助:

我想使用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();

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

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

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