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

1、new一个RestTemplate:

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

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

List> 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);

你可能感兴趣的:(java后台开发,srpingboot)