Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java UTF-8 encoding not working HttpURLConnection

Tags:

java

I tried to do post call and to pass input with this value - "ä€愛لآहที่" I got error message

{"error":{"code":"","message":{"lang":"en-US","value":{"type":"ODataInputError","message":"Bad Input: Invalid JSON format"}}}}

This is my code

    conn.setRequestMethod(ConnectionMethod.POST.toString());
    conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(content.getBytes().length));
    conn.setRequestProperty("Accept-Charset", "UTF-8"); 
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(content);
    wr.flush();
    wr.close();
    InputStream resultContentIS;
    String resultContent;
    try {
        resultContentIS = conn.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

it falied on conn.getInputStream();

The value of content is

{ "input" : "ä€愛لآहที่" }

It is working where the input is String or integer

When I added the statement

   conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); 

I got different message

 {"error":{"code":"","message":{"lang":"en-US","value":{"type":"Error","message":"Internal server error"}}}}
like image 786
user1365697 Avatar asked Sep 12 '13 08:09

user1365697


3 Answers

Please try this code below:

DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(content);
writer.close();
wr.close();

You should use JSONObject to pass params

The input, please try

BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS, "UTF-8"));

If the out put is: ???????, so do not worry because your output console do not support UTF-8

like image 130
Ha Nguyen Avatar answered Sep 27 '22 17:09

Ha Nguyen


It seems that your variable content does already have the wrong data because you may have converted a String without any attention to the required encoding.

Setting the correct enconding on the writer and use write() instead of writeBytes() should be worth a try.

like image 44
roehrijn Avatar answered Sep 27 '22 17:09

roehrijn


You have to send content via byte array

 DataOutputStream outputStream= new DataOutputStream(conn.getOutputStream());
 outputStream.write(content.toString().getBytes());

This is completely solution for your file name character problems. The imported point is string sending via byte array. Every character changing via byte character. This is prevent your character encoding problems.

like image 20
The Goat Avatar answered Sep 27 '22 16:09

The Goat