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

2024-02-09

我已经花了半个星期天的时间来解决这个问题,现在我需要帮助:

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

Example:



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

My code:

        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();

有任何想法吗?


您需要在您的中设置编码Content-Type header.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 HttpURLConnection 发送 UTF-8 字符失败 的相关文章

随机推荐