java调用天气预报接口案例

2018-09-10 01:02:17来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

免费天气接口: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();
    }
}

 

返回数据:

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:项目中遇到的问题——jsp:include

下一篇:异常处理