使用RestTemplate调用微信小程序接口出现HttpMessageConverter转换异常

1. 报错信息

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class xxx] and content type [text/plain]

2. 解决方法

添加以下配置

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        //先获取到converter列表
        RestTemplate restTemplate = builder.build();
        List> converters = restTemplate.getMessageConverters();
        for (HttpMessageConverter converter : converters) {
            //添加jsonConverter支持对text/plan的解析
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                try {
                    List mediaTypeList = new ArrayList<>(converter.getSupportedMediaTypes());
                    //加入对text/plan的支持
                    mediaTypeList.add(MediaType.TEXT_PLAIN);
                    //将已经加入了text/plan的MediaType支持列表设置为其支持的媒体类型列表
                    ((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(mediaTypeList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        restTemplate.setRequestFactory(clientHttpRequestFactory());
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(10000);
        return factory;
    }
}

添加maven依赖

        
            org.apache.httpcomponents
            httpclient
        

 

你可能感兴趣的:(Spring,java,spring)