【六袆-Java】springboot调用中国天气第三方接口;获取指定城市的天气;存储在redis里面;

一、准备数据

API:http://www.weather.com.cn/data/sk/城市ID.html

  • 例如,指定获取广州城市的天气
  • API : http://www.weather.com.cn/data/sk/101280101.html

 

1.Controller层

    /**
     * 获取天气
     * @return null
     * @throws Exception
     */
    @GetMapping("/farmer/getWeather")
    @ApiOperation("获取天气-赣州")
    public ResponseResult getWeather() throws Exception {
        return orchardJobService.getWeather();
    }

 

2.Service层


    /**
     * 获取天气
     * @return
     */
    public ResponseResult getWeather() throws Exception {
        ResponseResult responseResult = new ResponseResult();
        String weahter;
        if (!redisTemplate.hasKey("weather3")) {
            URL url = new URL("http://www.weather.com.cn/data/sk/101240701.html");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            byteArrayOutputStream.close();
            byte[] result = byteArrayOutputStream.toByteArray();
            weahter = new String(result, "utf-8");
            redisTemplate.opsForValue().set("weather3", weahter, 60 * 60 * 6, TimeUnit.SECONDS);
        } else {
            //通过键取值
            weahter =(String) redisTemplate.opsForValue().get("weather3");
        }
        return new ResponseResult(weahter);
    }

 

3.预览

 http://www.weather.com.cn/data/sk/101240701.html

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值