Search code examples
javajsonstringutf-8json-deserialization

how to set utf in HTTP GET, using JAVA


I am receiving special character as "ñ" or "á , é" etc in a response of Get request . The code is the next :

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
BufferedReader b_r = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String data = b_r.readLine();

How can I set utf-8 in order to receive the proper characters?


Solution

  • Ideally, don't use this code at all - use a JSON parser which accepts an InputStream, instead of reading it line by line.

    If you need, specify UTF-8 as the encoding to the InputStreamReader, as you're currently just using the platform default encoding:

    BufferedReader b_r = new BufferedReader(
        new InputStreamReader((connection.getInputStream(), StandardCharsets.UTF_8)));
    

    This is assuming it really is UTF-8 - which it should be, if it's JSON. (If the server isn't sending UTF-8, you should try to get that fixed.)