访问google的地图数据网站,取得json文件,并对其进行解析. 取出其中的位置信息数据.
解决问题的关键是:直接取得字节流,不要使用编码。
使用ByteArrayOutputStream
StringBuilder stringBuilder = new StringBuilder();
try {
String strUrl = String
.format(
"http://maps.google.com/maps/api/geocode/json?latlng=%s&sensor=true",
latlng);
Log.v(TAG, " strUrl = " + strUrl);
URL googleUrl = new URL(strUrl);
int count = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpURLConnection http = (HttpURLConnection) googleUrl
.openConnection();
http.setConnectTimeout(5 * 1000);
http.setRequestProperty("Accept-Language", "zh-CN");//向网站发起中文请求
http.setRequestProperty("Charset", "UTF-8"); //设置本地字符集
InputStream inStream = http.getInputStream(); //取得字节流
byte[] buf = new byte[512];
int ch = -1;
while ((ch = inStream.read(buf)) != -1) {
baos.write(buf, 0, ch); //把字节流以字节的方式写入ByteArrayOutputStream 中。
count = count + ch;
}
stringBuilder.append(new String(baos.toByteArray(), "UTF-8")); //对取得的字节流以UTF-8解码。
本文介绍了一种通过HTTP请求从Google地图API获取地理位置JSON数据的方法,并详细展示了如何使用Java代码直接读取字节流,避免编码问题,最终将数据解析为可读格式。

被折叠的 条评论
为什么被折叠?



