springboot用HttpClient调用天气预报接口
时间: 2024-02-19 11:30:06 浏览: 17
以下是使用HttpClient调用天气预报接口的Spring Boot示例:
1. 添加HttpClient和Jackson依赖
```xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
```
2. 创建HttpClient实例
```java
@Configuration
public class HttpClientConfig {
@Bean
public CloseableHttpClient httpClient() {
return HttpClients.createDefault();
}
@Bean
public HttpClientService httpClientService(CloseableHttpClient httpClient) {
return new HttpClientService(httpClient);
}
}
```
3. 创建HttpClientService类
```java
public class HttpClientService {
private final CloseableHttpClient httpClient;
public HttpClientService(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}
public String get(String url) throws IOException {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
} finally {
response.close();
}
return null;
}
}
```
4. 创建Weather类
```java
public class Weather {
private String date;
private String week;
private String weather;
private String temp;
private String humidity;
private String wind;
// getter and setter
}
```
5. 创建WeatherService类
```java
@Service
public class WeatherService {
private final HttpClientService httpClientService;
public WeatherService(HttpClientService httpClientService) {
this.httpClientService = httpClientService;
}
public List<Weather> getWeather(String city) throws IOException {
String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
String json = httpClientService.get(url);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
JsonNode dataNode = rootNode.path("data");
List<Weather> weatherList = new ArrayList<>();
for (JsonNode node : dataNode.path("forecast")) {
Weather weather = mapper.treeToValue(node, Weather.class);
weatherList.add(weather);
}
return weatherList;
}
}
```
6. 测试WeatherService
```java
@RestController
public class WeatherController {
private final WeatherService weatherService;
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@GetMapping("/weather")
public List<Weather> getWeather(@RequestParam String city) throws IOException {
return weatherService.getWeather(city);
}
}
```
现在,你可以通过访问http://localhost:8080/weather?city=北京来获取北京的天气预报信息。