关于api:Java-聚合数据API接口调用城市天气预报

47次阅读

共计 3517 个字符,预计需要花费 9 分钟才能阅读完成。

点击进入【数据聚合_数据接口调用_开发者数据 API 开放平台】(官网)

在 pom 文件中,退出依赖

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier>
        </dependency>

SimpleWeather.java

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class SimpleWeather {
    // 天气情况查问接口地址
    public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";
    // 接口申请 Key
    public static String API_KEY = "108f91d439908e5d2da86cc8881dd3db";
    public static void main(String[] args) {
        String cityName = "北京";
        queryWeather(cityName);
    }
    /**
     * 依据城市名查问天气情况
     *
     * @param cityName
     */
    public static void queryWeather(String cityName) {Map<String, Object> params = new HashMap<>();// 组合参数
        params.put("city", cityName);
        params.put("key", API_KEY);
        String queryParams = urlencode(params);
        String response = doGet(API_URL, queryParams);
        try {JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {System.out.println("调用接口胜利");
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject realtime = result.getJSONObject("realtime");
                System.out.printf("城市:%s%n", result.getString("city"));
                System.out.printf("天气:%s%n", realtime.getString("info"));
                System.out.printf("温度:%s%n", realtime.getString("temperature"));
                System.out.printf("湿度:%s%n", realtime.getString("humidity"));
                System.out.printf("风向:%s%n", realtime.getString("direct"));
                System.out.printf("风力:%s%n", realtime.getString("power"));
                System.out.printf("空气质量:%s%n", realtime.getString("aqi"));
            } else {System.out.println("调用接口失败:" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {e.printStackTrace();
        }
    }
    /**
     * get 形式的 http 申请
     *
     * @param httpUrl 申请地址
     * @return 返回后果
     */
    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回后果字符串
        try {
            // 创立近程 url 连贯对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过近程 url 连贯对象关上一个连贯,强转成 httpURLConnection 类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连贯形式:get
            connection.setRequestMethod("GET");
            // 设置连贯主机服务器的超时工夫:15000 毫秒
            connection.setConnectTimeout(5000);
            // 设置读取近程返回的数据工夫:60000 毫秒
            connection.setReadTimeout(6000);
            // 发送申请
            connection.connect();
            // 通过 connection 连贯,获取输出流
            if (connection.getResponseCode() == 200) {inputStream = connection.getInputStream();
                // 封装输出流,并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();}
        } catch (IOException e) {e.printStackTrace();
        } finally {
            // 敞开资源
            if (null != bufferedReader) {
                try {bufferedReader.close();
                } catch (IOException e) {e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {inputStream.close();
                } catch (IOException e) {e.printStackTrace();
                }
            }
            if (connection != null) {connection.disconnect();// 敞开近程连贯
            }
        }
        return result;
    }
    /**
     * 将 map 型转为申请参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, ?> data) {StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}

启动程序,呈现如下成果

—————————————
版权申明:本文为 CSDN 博主「法海你为啥不懂爱」的原创文章,遵循 CC 4.0 BY-SA 版权协定,转载请附上原文出处链接及本申明。
原文链接:https://blog.csdn.net/CSDN_ja…

正文完
 0