android天气软件开发随笔(一)——城市列表返回

来源:互联网 发布:描写恋人相遇的数据 编辑:程序博客网 时间:2024/06/06 05:46

问题

使用百度apistore来获取天气数据,在手机上查询城市列表时,按照要求输入城市名称,却无法得到在网页上使用API调试工具所得到的答案

解决

URL请求连接是不支持中文的,可以将中文改写成UTF-8的编码格式,然后发送URL请求,最终将得到你说需要的文件。

解决代码示例

String cityName = "北京";cityName = URLEncoder.encode(cityName, "UTF-8");StringBuilder addressBuilder = new StringBuilder();  addressBuilder.append("http://apis.baidu.com/apistore/weatherservice/citylist");addressBuilder.append("?");addressBuilder.append("cityname=");addressBuilder.append(cityName);String httpUrl = addressBuilder.toString();//当然,网络请求需要进行异步操作的 HttpURLConnection connection = null;                try{                    URL url = new URL(httpUrl);                    connection = (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setRequestProperty("apikey", apikey);                    InputStream in = connection.getInputStream();                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));                    StringBuilder response = new StringBuilder();                    String line;                    while((line = reader.readLine()) != null){                        response.append(line);                    }                    reader.close();                    //result就是所需要的JSON数据                    String result = response.toString();                }catch (Exception e){                    e.printStackTrace();                }
0 0