package com.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import java.nio.charset.Charset; @Configuration public class RestTemplateConfig { @Autowired private RestTemplateBuilder builder; @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = builder.build(); restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(Charset.forName("ISO-8859-1"))); return restTemplate; } }
dataStr=new String(dataStr.getBytes("UTF-8"),"ISO-8859-1");
/** * * @param url 第三方接口 * @return */ private Weather doGetData(String url) { //头部信息定义end try { ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); if(response.getStatusCode() == HttpStatus.OK) { //开始gzip解码 InputStream inWithCode = new ByteArrayInputStream(response.getBody().getBytes("ISO-8859-1")); GZIPInputStream gunzip = new GZIPInputStream(inWithCode); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer))>= 0) { out.write(buffer, 0, n); } //gzip解码结束 String dataStr = out.toString(); //将数据封装到WeatherResponse对象中 WeatherResponse wr = new ObjectMapper().readValue(dataStr, WeatherResponse.class); if(wr.getStatus().equals("1000")) { //返回响应数据 return wr.getData(); }else { throw new BusinessException("call weather api error"); } }else { throw new BusinessException("call weather api error"); } }catch(BusinessException e) { throw e; }catch(Exception e) { throw new BusinessException("call weather api error", e); } }
RestTemplate调用三方接口获取数据时出现乱码的常见解决办法
原文:https://www.cnblogs.com/mogong/p/12571344.html