查看响应数据的编码格式是否正确
- 若不正确可在RestTemplate注入spring容器时进行修改,如下
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");
查看接口返回的内容编码是否为gzip
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8a0351d7e7188ca70ebe1527f36c0d87.png)
private Weather doGetData(String url) {
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
if(response.getStatusCode() == HttpStatus.OK) {
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);
}
String dataStr = out.toString();
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);
}
}