最近在做一个请求天气数据的功能,发现其实很多接口都是可以输入中文的,但是在输入中文的后,请求数据却是铁定的不会成功。研究了一下后知道了原因,原来是在URL地址中所谓的汉字最后都做了转码,将汉字转成一群乱码,然后发送至服务器请求json或者xml数据。废话不多说,上源码:
package com.hisign.csipadmini_free.biz; import java.io.UnsupportedEncodingException;/** * 描述:url解码,转码 * 公司: * 作者:octopus * 创建时间 2016/10/18 */public class UrlUtil { private final static String ENCODE = "UTF-8"; /** * URL 解码 * @param str * @return */ public static String getURLDecoderString(String str) { String result = ""; if (null == str) { return ""; } try { result = java.net.URLDecoder.decode(str, ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } /** * URL 转码 * @param str * @return */ public static String getURLEncoderString(String str) { String result = ""; if (null == str) { return ""; } try { result = java.net.URLEncoder.encode(str, ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }}
接下来只要将其拼入URL地址中就好了,
** * 按城市名请求,温度 * @param cityName */ public void requestTemperatureWithHttpClient(String cityName){ if (cityName.endsWith(getResourceStr(R.string.str_char_city))){ cityName = cityName.substring(0,cityName.length()-1); } StringBuilder stringBuilder = new StringBuilder("http://api.map.baidu.com/telematics/v3/weather?location=") .append(getURLEncoderString(cityName)) .append("&output=json&ak=").append("nidebaiduMap apikey").append("&mcode=你的Mcode"); sendRequest(stringBuilder.toString()); }
private void sendRequest(final String urlstr) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(urlstr); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // Log.i("TAG", response.toString()); parseJSONToWeather(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); }再下来就是解析接收到的json字符串了,小菜一碟,祝好!