springboot 调用第三方天气接口

  1. 查询天气的api:https://www.sojson.com/open/api/weather/json.shtml?city="北京"

  2. 直接在city=后面加上中文城市,就会返回json数据。

  3. 基于maven创建一个springboot应用,pom信息如下,注意添加了httpclien

  4. pom导入 <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.7</version>
    </dependency>

 

创建配置类

package com.thundersdata.backend.basic.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author w
 * @Classname WeatherConfig
 * @Description TODO
 * @Date 2020/2/18 18:51
 */
@Configuration
public class WeatherConfig {

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

Controller接口

package com.thundersdata.backend.basic.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author w
 * @Classname QueryWeatherController
 * @Description TODO
 * @Date 2020/2/18 18:46
 */
@Api(tags = "天气查询接口")
@RestController
@RequestMapping("QueryWeather")
public class QueryWeatherController {

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value = "天气查询接口", notes = "返回最近7天天气预报")
    @GetMapping
    public String QueryWeather() {
        String apiURL = "http://wthrcdn.etouch.cn/weather_mini?city=" + "北京";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiURL, String.class);

        if (200 == responseEntity.getStatusCodeValue()) {
            return responseEntity.getBody();
        } else {
            return "error with code : " + responseEntity.getStatusCodeValue();
        }
    }
}

运行程序调用一下就可以返回最近7天的天气预报了

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值