今天在使用spring提供的RestTemplate发送请求调用第三方接口时,返回的中文值乱码,代码如下:
String url=host+"/api/cctv/camera/list";
HttpHeaders headers=new HttpHeaders();
headers.set("Authorization", "Bearer 854490fc-9c45-42f1-bf02-ad5a63b72831");
headers.set("Content-Type", "application/json");
String requestBody="{\r\n" +
" \"current\":"+current+",\r\n" +
" \"size\":"+size+",\r\n" +
" \"provinceList\":[\"HaiNan\"]\r\n" +
"}";
HttpEntity<String> entity=new HttpEntity<>(requestBody,headers);
ResponseEntity<String> response = template.exchange(url, HttpMethod.POST, entity, String.class);
String sttr = response.getBody();
System.out.println(sttr);
输出结果中文乱码。解决方法是将返回值转码,代码如下:
String sttr = new String(response.getBody().toString().getBytes("ISO-8859-1"),"UTF-8");
解决办法很简单,这里记录一下解决历程:
首先项目采用UTF-8编码,所以肯定要转换成UTF-8格式。
那么接口本身返回的值是什么编码呢?我们知道,http请求默认是供浏览器请求的,浏览器支持的编码是ISO-8859-1,由此,猜测是ISO-8859-1。
还有一种高级的解决办法:
通过查看RestTemplate的构造方法,查看其默认的编码方式,构造函数代码如下:
public RestTemplate() {
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter());
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
this.messageConverters.add(new AtomFeedHttpMessageConverter());
this.messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
}
else if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
}
其中MessageConverts就是在做消息的转换,我们业务代码中转成了String,所以查看new StringHttpMessageConverter()的源码:
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
}
然后查看DEFAULT_CHARSET,
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
由此可知,是ISO-8859-1