Android 使用url获取数据时的文字编码问题

来源:互联网 发布:2016网络犯罪案例 编辑:程序博客网 时间:2024/04/30 17:14

今天使用百度地图的LBS云检索的nearby时发现一直返回region错误或无法找到结果的返回结果,感觉很奇怪,

把log出来的URL贴到浏览器打开结果却是正确的。


一开始怀疑是编码问题于是把整个URL转化为UTF-8发现有错误。


后来解决的方法是:

把中文部分单独转化成UTF-8后再与URL其他部分拼装


/** * GET方式获取JSON数据 * @param type 查询类型 LOCAL周边检索输地名 NEARBY本地检索输坐标 * @param location nearby检索时的检索中心点坐标 * @param radius nearby检索时的检索半径 单位米 * @param region local检索时的检索地点 e.g. 北京市/福建师范大学/安徽省 * @return jsonStr 返回JSON数据的String值 * @throws Exception  */public static String getParkData(String type,String location,int radius,String region) throws Exception{if (type.equals("NEARBY")) {path = SEARCH_URL_NEARBY + "?ak=" + API_KEY + "&geotable_id="+ GEOTABLE_ID + "&mcode=" + MCODE + "&location=" + location + "&radius="+ radius ;}else if(type.equals("LOCAL")){region = URLEncoder.encode(region, "UTF-8");path = SEARCH_URL_LOCAL + "?region=" + region + "&ak=" + API_KEY + "&geotable_id="+ GEOTABLE_ID + "&mcode=" + MCODE ;}else{return null;}Log.i("url", path);//path = URLEncoder.encode(path,"UTF-8");URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(TIMEOUTMILL);connection.setRequestMethod("GET");if(connection.getResponseCode() == RESPONSESUCCESS){InputStream is = connection.getInputStream();byte[] data = readStream(is);String jsonStr = new String(data);Log.i("json", "json解析时的path : "+path);Log.i("json", "jsonStr: "+jsonStr);return jsonStr;}else{return null;}}


0 0
原创粉丝点击