先写url返回json字符串的响应类WeatherResponse以及其它实体类
private static Logger log=LoggerFactory.getLogger(WeatherServiceImpl.class);
private static final String URI="http://wthrcdn.etouch.cn/weather_mini?";//第三方接口的uri
@Autowired
private RestTemplate restTemplate;
/**
* 根据城市id获取天气数据
*/
@Override
public WeatherResponse getWeatherByCityId(String cityId)
{
WeatherResponse weatherResponse=null;
//第一步:访问第三方接口的url
String url=URI+"citykey="+cityId;
log.info(url);
//第二步:RestTemplate访问url获取json字符串
ResponseEntity<String> response=restTemplate.getForEntity(url, String.class);
//response是响应,但是这个天气的json字符串表示对应的是response的响应体,也就是body
/*
* 第三步:把json串(response.getBody())转成Object
* 1.需要一个工具类:ObjectMapper方法readValue(String,Class)
*/
ObjectMapper objMapper=new ObjectMapper();//jackson提供工具类
String strBody=null;
if(response.getStatusCodeValue()==200)
{
//2.先获取响应体
strBody=response.getBody();
}
//3.把strBody转化成java类
try {
weatherResponse=objMapper.readValue(strBody, WeatherResponse.class);
} catch (Exception e) {
log.info("objMapper resdValue异常");
}
return weatherResponse;
}
其中的RestTemplate需要特殊处理一下
import java.nio.charset.StandardCharsets;
import org.springframework.boot.web.client.RestTemplateBuilder;
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;
@Configuration
public class RestConfig {
/**
* 因为访问天气url的响应数据是压缩格式的,所以当前这个bean要特殊处理一下
* @return
*/
@Bean
public RestTemplate createRestTemplate(RestTemplateBuilder builder)
{
//能够使用heetClient访问url,支持响应回来的GZIP格式
RestTemplate restTemplate=new RestTemplate(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
}