Send UTF-8 characters via HttpURLConnection crash

I spent half Sunday, now I need help:

I want to send a string including UTF-8 special characters encoded on the server using Java HttpURLConnection. Correct character encoding does not work.

Example:

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

My code is:

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?

+4
source share
1 answer

You need to set the encoding in the Content-Type header.

Set the value to " application/x-www-form-urlencoded; charset=utf-8 ". Currently you only install accept-charset - this tells the server what to send back.

+7
source

All Articles