springboot连接天气api
时间: 2023-09-30 08:09:31 浏览: 47
连接天气 API 可以使用 Spring Boot 的 RestTemplate 组件来实现。以下是一个示例代码:
```java
@Service
public class WeatherService {
private final RestTemplate restTemplate;
private final String apiUrl = "http://api.openweathermap.org/data/2.5/weather?q={city}&appid={apiKey}";
@Autowired
public WeatherService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public WeatherData getWeather(String city, String apiKey) {
ResponseEntity<WeatherData> response = restTemplate.getForEntity(apiUrl, WeatherData.class, city, apiKey);
if (response.getStatusCode() == HttpStatus.OK) {
return response.getBody();
} else {
throw new RuntimeException("Failed to get weather data");
}
}
}
```
在上面的代码中,我们使用了 `RestTemplate` 组件来发起 HTTP 请求。我们将服务端点 URL 和 API 密钥存储在类变量中,并在 `getWeather` 方法中将城市名和 API 密钥作为参数传递给服务端点 URL。在成功获取响应后,我们将其转换为 `WeatherData` 对象并返回它。
最后,您需要在 Spring Boot 应用程序中配置 `RestTemplate`,您可以在 `@Configuration` 类中添加以下代码:
```java
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
```
这样就完成了连接天气 API 的操作。您可以在 `WeatherData` 类中定义所需的模型类以存储 API 响应数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)