调用聚合数据平台天气接口

1.进入聚合数据进行注册、实名认证、领取免费天气API接口

聚合数据官网
①进入官网后注册(此步骤忽略自行操作)
②个人中心->账号管理->实名认证
③搜索框中输入天气关键字、免费领取天气预报API
在这里插入图片描述
④进入个人中心->数据中心就可以看见领取的天气API
在这里插入图片描述

可以进入测试界面尝试测试一下API在这里插入图片描述
可以看到请求详情的一些参数:请求地址、请求参数、请求方式、请求头
细心的小伙伴会注意到两个参数的不同,其中参数一:city表示我们要查询出哪一座城市的天气数据,但是明显城市名被进行了编码操作。参数二: key与下图的请求key是一致的
在这里插入图片描述

2.编写代码测试接口

测试代码前需要在项目工程中引入fastjson2jar包
在这里插入图片描述

public class WeatherAPITest {
    public static final String API_URL = "http://apis.juhe.cn/simpleWeather/query"; // 请求第三方服务器地址
    public static final String API_KEY = "515a64ce1d92c586076ef2ed55bab33e"; // 请求key
    public static final int RESULT_CODE = 200; // 响应结果

    public static void main(String[] args) {
        JSONObject jsonObject = queryWeather("上海");
        System.out.println(jsonObject);
    }


    public static JSONObject queryWeather(String city) {
        JSONObject jsonObject = null;
        HashMap<String, String> params = new HashMap<>();
        params.put("city",city);
        params.put("key",API_KEY);
        // 请求参数进行编码操作
        String requestParams = paramsEncode(params);
        // 请求第三方服务器
        String response = doGet(API_URL, requestParams);
        try {
            jsonObject = JSONObject.parseObject(response);
            int errorCode = jsonObject.getInteger("error_code");
            if (errorCode == 0) {
                System.out.println("调用接口成功");
            } else {
                System.out.println("调用接口失败:" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
      return jsonObject;
    }

    /**
     * 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(httpUrl + "?" + queryParams);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == RESULT_CODE) {
                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);
                }
                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;
    }

    /***
     *
     * @param param 请求参数
     * @return 编码过后的请求参数
     */
    public static String paramsEncode(HashMap<String, String> param) {
        StringBuffer str = new StringBuffer();
        for (Map.Entry<String, String> res : param.entrySet()) {
            try {
                str.append(res.getKey()).append("=").append(URLEncoder.encode(res.getValue(), "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        int index = str.lastIndexOf("&");
        return str.toString().substring(0, index);
    }
}

结果展示:

{
	"reason":"查询成功!",
	"result":{
		"city":"上海",
		"realtime":{
			"temperature":"11",
			"humidity":"52",
			"info":"多云",
			"wid":"01",
			"direct":"西风",
			"power":"2级",
			"aqi":"35"
		},
		"future":[
			{
				"date":"2022-12-06",
				"temperature":"6\/13℃",
				"weather":"多云",
				"wid":{
					"day":"01",
					"night":"01"
				},
				"direct":"东北风"
			},
			{
				"date":"2022-12-07",
				"temperature":"11\/14℃",
				"weather":"多云转阴",
				"wid":{
					"day":"01",
					"night":"02"
				},
				"direct":"东风"
			},
			{
				"date":"2022-12-08",
				"temperature":"10\/14℃",
				"weather":"小雨转阴",
				"wid":{
					"day":"07",
					"night":"02"
				},
				"direct":"东风转东北风"
			},
			{
				"date":"2022-12-09",
				"temperature":"10\/13℃",
				"weather":"阴转多云",
				"wid":{
					"day":"02",
					"night":"01"
				},
				"direct":"东北风转西北风"
			},
			{
				"date":"2022-12-10",
				"temperature":"8\/13℃",
				"weather":"晴",
				"wid":{
					"day":"00",
					"night":"00"
				},
				"direct":"西北风"
			}
		]
	},
	"error_code":0
}

至此调用聚合数据平台天气接口就演示完毕。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值