您的位置:首页 > 理论基础 > 计算机网络

访问网络资源,并显示成中文,解决中文乱码问题.

2011-05-13 13:22 351 查看
访问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解码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: