In my app a try to get location names via tapping on google map. Everything works fine except for the character encoding.
My output is like:
1144 Budapest, Ond vezér útja 35, Hungary
How could i set character encoding to get the correct response like:
1144 Budapest, Ond vezér útja 35, Hungary
I tried with .setHeader("Accept-Charset", "utf-8");
but not working this way.
Code:
public static JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true");
httpGet.setHeader("Accept-Charset","utf-8");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
E D I T:
I made this work with:
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
Thanks for the answer.
This is the problem:
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
That's effectively using ISO-8859-1.
Instead, you should create an InputStreamReader
from the InputStream
, specifying UTF-8 as the encoding (as that's what you say you accept), and then read from that. You could read from it directly, or use something like Guava and CharStreams.toString
:
InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
String text = CharStreams.toString(reader);
See more on this question at Stackoverflow