SpringTemplate no suitable HttpMessageConverter found for response type

前端 未结 1 1819
清歌不尽
清歌不尽 2021-01-12 15:51

I am getting the following error while using spring rest template but i have defined jackson for json responses.

As well when I query to the url with rest client i g

相关标签:
1条回答
  • 2021-01-12 16:39

    Default media type for MappingJackson2HttpMessageConverters is

    /**
     * Construct a new {@code BindingJacksonHttpMessageConverter}.
     */
    public MappingJackson2HttpMessageConverter() {
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }
    

    You can specify media type for MappingJackson2HttpMessageConverter in your bean definition, like this

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
                jsonConverter.setObjectMapper(new ObjectMapper());
                jsonConverter.setSupportedMediaTypes(ImmutableList.of(new MediaType("application", "json", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET), new MediaType("text", "javascript", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET)));
            }
        }
        return restTemplate;
    }
    

    or using wildcard

    jsonConverter.setSupportedMediaTypes(ImmutableList.of(new MediaType("*", "json", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET), new MediaType("*", "javascript", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET)));
    
    0 讨论(0)
提交回复
热议问题