目录
问题
在使用RestTemplate
方法:postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)
返回的中文乱码,如下:
排查问题
查看RestTemplate的构造函数,发现StringHttpMessageConvert默认的编码是ISO-8859-1,源码如下:
修改问题:
List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
httpMessageConverters.stream().forEach(httpMessageConverter -> {
if(httpMessageConverter instanceof StringHttpMessageConverter){
StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
//设置编码为UTF-8
messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
}
});
//发送POST请求
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
测试
至此,乱码问题修复