在我的应用程序中尝试通过点击谷歌地图获取位置名称。 除了字符编码外,一切正常。
我的输出是这样的:
1144 Budapest, Ond vezér ãºtja 35, Hungary
我如何设置字符编码以获得正确的响应,例如:
1144 Budapest, Ond vezér útja 35, Hungary
我尝试使用 .setHeader("Accept-Charset", "utf-8");
但不是这样工作的。
代码:
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;
}
编辑:
我用以下方法完成了这项工作:
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
感谢您的回答。
最佳答案
问题是:
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
这有效地使用了 ISO-8859-1。
相反,您应该从 InputStream
创建一个 InputStreamReader
,将 UTF-8 指定为编码(因为这就是您所说的您接受的编码),然后从中读取.您可以直接从中读取,或使用类似 Guava 的内容和 CharStreams.toString
:
InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
String text = CharStreams.toString(reader);
关于android - 尝试使用 google 的地理编码 api 获取位置信息时出现奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23327557/