现象描述
使用RestTemplate 发送http请求,调用接口,返回的结果中,出现中文乱码情况
代码片段
ResponseEntity<String> response = restTemplate.getForEntity(oraPatrolItemListUrl, String.class); String body = response.getBody(); System.out.println(body);
问题查找
找到RestTemplate 的初始化配置类
@Configuration public class RestTemplateConfig{ private int timeoutms = 5 * 60 *1000; @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory);; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(timeoutms);//ms factory.setConnectTimeout(timeoutms);//ms return factory; } }
需要对该配置类进行改造一下哦
具体改造方法
方式一(推荐):
package com.xxl.job.executor.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.List; @Configuration public class RestTemplateConfig{ private int timeoutms = 5 * 60 *1000; @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ RestTemplate restTemplate = new RestTemplate(factory); List<HttpMessageConverter<?>> converterList =restTemplate.getMessageConverters(); int converterIndex = -1; for (int i=0;i<converterList.size();i++){ if(converterList.get(i).getClass() == StringHttpMessageConverter.class){ converterIndex = i; break; } } if(converterIndex !=-1) { restTemplate.getMessageConverters().set(converterIndex, new StringHttpMessageConverter(StandardCharsets.UTF_8)); } return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(timeoutms);//ms factory.setConnectTimeout(timeoutms);//ms return factory; } }
方式二:(简单版,不推荐)
@Configuration public class RestTemplateConfig{ private int timeoutms = 5 * 60 *1000; @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(timeoutms);//ms factory.setConnectTimeout(timeoutms);//ms return factory; } }
改造完成之后,在调用一下接口,发现不再乱码了