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

6

我已经花了半个星期天在这上面,现在我需要帮助:

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

有什么想法吗?


在设置accept-charset和content-type属性之后,或许需要设置setDoOutput(true)吗? - Sterpu Mihai
没有,没有帮助。谢谢你的想法! - Martin Ho
1
你的Content-Type头应该是application/x-www-form-urlencoded; charset=utf-8。你还需要确保你的服务器注意到这一点,并将其作为UTF-8读取。你能发布你的服务器代码吗? - Boris the Spider
1个回答

8

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接