zoukankan      html  css  js  c++  java
  • 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();
        }
    }

    返回数据:

     

  • 相关阅读:
    maskrcnn_benchmark代码分析(2)
    NoSQL现状
    CAP理论
    svn revert
    在SpringMVC中使用Jackson并格式化时间
    找了一个api管理工具
    SpringBoot读取application.properties文件
    MySQL性能优化的21个最佳实践 和 mysql使用索引
    Cannot subclass final class class com.sun.proxy.$Proxy
    AOP拦截器 表达式写法
  • 原文地址:https://www.cnblogs.com/hhmm99/p/9599417.html
Copyright © 2011-2022 走看看