springboot调用天气预报接口
时间: 2023-09-14 08:11:45 浏览: 107
Spring Boot可以使用RestTemplate来调用天气预报接口。以下是一个简单的示例:
1.添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
```
2.创建一个Weather类
```java
public class Weather {
private String city;
private String temperature;
private String description;
// 省略getter和setter方法
}
```
3.创建一个WeatherService类
```java
@Service
public class WeatherService {
private RestTemplate restTemplate;
@Autowired
public WeatherService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public Weather getWeather(String city) {
String url = "http://api.openweathermap.org/data/2.5/weather?q={city}&appid={appId}&units=metric";
String appId = "your_app_id_here"; // 请替换成你自己的App ID
Map<String, String> params = new HashMap<>();
params.put("city", city);
params.put("appId", appId);
WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class, params);
Weather weather = new Weather();
weather.setCity(response.getName());
weather.setTemperature(response.getMain().getTemp() + " °C");
weather.setDescription(response.getWeather().get(0).getDescription());
return weather;
}
}
```
注意:这里WeatherResponse类是用来解析JSON响应的,需要根据接口返回的JSON数据结构自行编写。
4.创建一个WeatherController类
```java
@RestController
public class WeatherController {
private WeatherService weatherService;
@Autowired
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@GetMapping("/weather/{city}")
public Weather getWeather(@PathVariable String city) {
return weatherService.getWeather(city);
}
}
```
现在可以启动应用程序并访问http://localhost:8080/weather/{city}来获取指定城市的天气预报。
阅读全文