通过HttpURLConnection发送UTF-8字符失败 [英] Send UTF-8 chars via HttpURLConnection failing
本文介绍了通过HttpURLConnection发送UTF-8字符失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经花了一半星期天,我现在需要帮助:
I have spent half Sunday on this now I need help:
我想使用Java HttpURLConnection向服务器发送一个包含特殊字符UTF-8编码的字符串。字符的正确编码失败。
I want to send a String including special chars UTF-8 encoded to a server using Java HttpURLConnection. The correct encoding of the chars fails.
示例:
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();
任何想法?
推荐答案
您需要在 Content-Type
标题中设置编码。
You need to set the encoding in your Content-Type
header.
设置它到 application / x-www-form-urlencoded; charset = utf-8
。目前你只设置 accept-charset
- 这告诉服务器要发回什么。
Set it to "application/x-www-form-urlencoded; charset=utf-8
". Currently you only set the accept-charset
- this tells the server what to send back.
这篇关于通过HttpURLConnection发送UTF-8字符失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文