java 通过 HttpURLConnection 发送 UTF-8 字符失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15865561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send UTF-8 chars via HttpURLConnection failing
提问by Martin Ho
I have spent half Sunday on this now I need help:
我已经花了半个星期天,现在我需要帮助:
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.
我想使用 Java HttpURLConnection 将包含特殊字符 UTF-8 编码的字符串发送到服务器。字符的正确编码失败。
Example:
例子:
strToSend: ? ù strUrlEncoded: %C3%A4+%C3%B9+%E2%82%AC strReceived:?¤ ?1 a?
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();
Any ideas?
有任何想法吗?
回答by Boris the Spider
You need to set the encoding in your Content-Type
header.
您需要在Content-Type
标头中设置编码。
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.
将其设置为“ application/x-www-form-urlencoded; charset=utf-8
”。目前您只设置accept-charset
- 这告诉服务器要发回什么。