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

本文介绍了一种通过HTTP请求从Google地图API获取地理位置JSON数据的方法,并详细展示了如何使用Java代码直接读取字节流,避免编码问题,最终将数据解析为可读格式。

访问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解码。
   
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值