查看響應數據的編碼格式是否正確
- 若不正確可在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

/**
*
* @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);
}
}