![](/img/trans.png)
[英]Android/Java Send a http post request with chars not reformatted as UTF-8
[英]Send UTF-8 chars via HttpURLConnection failing
我現在已經花了一半星期天,我現在需要幫助:
我想使用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();
有任何想法嗎?
您需要在Content-Type
標頭中設置編碼。
將其設置為“ application/x-www-form-urlencoded; charset=utf-8
”。 目前你只設置了accept-charset
- 這告訴服務器要發回什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.