欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot中,RestTemplate中文乱码解决方案

程序员文章站 2022-05-30 23:42:16
...

1、new一个RestTemplate:

SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
httpRequestFactory.setReadTimeout(35000);
httpRequestFactory.setConnectTimeout(5000);
RestTemplate restTemplate = new RestTemplate(httpClientFactory);

2、重新设置restTemplate的messageConverters,否则用的默认的messageConverters。

List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        /** 解决乱码的converter */
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName
                ("UTF-8"));
        messageConverters.add(stringHttpMessageConverter);
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());
        RestTemplate restTemplate = new RestTemplate(httpClientFactory);
        restTemplate.setMessageConverters(messageConverters);