java调用天气预报接口案例

免费天气接口:http://mobile.weather.com.cn/data/sk/城市ID.html

例如: http://mobile.weather.com.cn/data/sk/101240701.html

返回数据:{"sk_info":{"date":"20131012","cityName":"赣州","areaID":"101240701","temp":"32℃","tempF":"89.6℉","wd":"东北风","ws":"3级","sd":"27%","time":"15:10","sm":"暂无实况"}}

城市编码点我下载

 

代码:

    @Test
    public void testetWeatherInfo(){
        //南昌天气预报信息
        String u="http://mobile.weather.com.cn/data/sk/101240101.html";
        String info=WeatherUtil.getWeatherInfo(u);
        //输出
        System.out.println("info:"+info);
    }

 

/**
 * @author hh
 */
public class WeatherUtil {
    /**
     * 获取天气信息
     * @param urlPath 请求链接  eg:http://mobile.weather.com.cn/data/sk/101240701.html
     * @return eg:{"sk_info":{"date":"20131012","cityName":"赣州","areaID":"101240701","temp":"32℃","tempF":"89.6℉","wd":"东北风","ws":"3级","sd":"27%","time":"15:10","sm":"暂无实况"}}
     */
    public static String getWeatherInfo(String urlPath){
        //拼接接收的信息
        StringBuffer info=new StringBuffer();
        //读取每行的数据
        String inputline="";
        try {
            //实例化URL对象
            URL url= new URL(urlPath);
            //获取应用程序和 URL 之间的通信链接
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
            // 请求方法
            conn.setRequestMethod("GET");
            //获取url的资源输入流
            InputStreamReader inReader=new InputStreamReader(conn.getInputStream(),"utf-8");
            //获取缓冲字符输入流
            BufferedReader bufferedReader=new BufferedReader(inReader);
            //读取每行数据(同时赋值,判断是否为空)
            while((inputline=bufferedReader.readLine())!=null){
                //添加信息
                info.append(inputline);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info.toString();
    }
}

 

返回数据:

 

 

posted @ 2018-09-06 16:57  黄浩#  阅读(1279)  评论(0编辑  收藏  举报