springboot之访问第三方接口RestTemplate访问url获取json字符串把json串(response.getBody())转成Object

先写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;
	}

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值