Ignacio Chiazzo Ignacio Chiazzo - 2 years ago 115
Java Question

how to set utf in HTTP GET, using JAVA

How to set UTF in JSON ? I receive a JSON with http get, and the JSON contains special character as "ñ" or "á , é" etc. The code is the next :

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

Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download