-
查询天气的api:https://www.sojson.com/open/api/weather/json.shtml?city="北京"
-
直接在city=后面加上中文城市,就会返回json数据。
-
基于maven创建一个springboot应用,pom信息如下,注意添加了httpclien
-
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天的天气预报了