springboot通过feign技术调用第三方天气预报接口并以json格式显示给前端
时间: 2024-01-07 17:05:58 浏览: 141
spring-boot-feign
1. 引入依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
```
2. 创建Feign接口
创建一个Feign接口来定义调用第三方天气预报接口的方法,该接口使用`@FeignClient`注解来指定要调用的服务名和服务地址。
```java
@FeignClient(name = "weather", url = "http://www.weather.com.cn")
public interface WeatherClient {
@GetMapping("/data/sk/{cityCode}.html")
String getWeather(@PathVariable("cityCode") String cityCode);
}
```
3. 创建Controller
创建一个Controller来处理前端的请求,该Controller使用`@RestController`注解来指定返回的结果是JSON格式的数据。
```java
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Autowired
private WeatherClient weatherClient;
@GetMapping("/{cityCode}")
public String getWeather(@PathVariable("cityCode") String cityCode) {
String result = weatherClient.getWeather(cityCode);
// 处理返回结果
return result;
}
}
```
4. 测试
启动SpringBoot应用,访问`http://localhost:8080/weather/101210101`,即可查看北京市的天气预报信息。
返回的结果如下所示:
```json
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"-2","WD":"西南风","WS":"2级","SD":"26%","AP":"1022hPa","njd":"暂无实况","WSE":"2","time":"17:55","sm":"1.1","isRadar":"1","Radar":""}}
```
通过以上步骤,我们成功地使用Feign技术调用了第三方天气预报接口,并以JSON格式显示给前端。
阅读全文