@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
// 支持中文编码
setRestTemplateEncode(restTemplate);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
public void setRestTemplateEncode(RestTemplate restTemplate) {
if (null == restTemplate || ObjectUtils.isEmpty(restTemplate.getMessageConverters())) {
return;
}
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
for (int i = 0; i < messageConverters.size(); i++) {
HttpMessageConverter<?> httpMessageConverter = messageConverters.get(i);
if (httpMessageConverter.getClass().equals(StringHttpMessageConverter.class)) {
messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
}
}
}
标签:中文,messageConverters,RestTemplate,restTemplate,factory,乱码,new,public
From: https://www.cnblogs.com/marchxd/p/16954595.html