RestTemplate报错:no suitable HttpMessageConverter found for request type

某天试用RestTemplate调试,浏览器直接提示:

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Dec 01 14:49:26 CST 2017

There was an unexpected error (type=Internal Server Error, status=500).

Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [application/x-www-form-urlencoded;charset=UTF-8]

 

查看后台是RestTemplate模板异常:

org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [application/x-www-form-urlencoded;charset=UTF-8]

 

异常提示已经很明显了,原因是由于我的post方法使用了MultiValueMap来封装参数,但是无法找到合适的类型转换,仔细查看我的RestTemplate对象获取方式是如下的:

     public static RestTemplate getInstance(String charset) {
          StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName(charset));
          RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build();
          return restTemplate;
     }

 

 

其实问题就出现在上面这段代码上面,我使用了RestTemplateBuilder来创建RestTemplate对象,该方式只会为restTemplate模板初始化一个HttpMessageConverter(注:StringHttpMessageConverter间接实现HttpMessageConverter接口)

 

RestTemplate报错:no suitable HttpMessageConverter found for request type_第1张图片

 

再比较直接 new RestTemplate()创建对象的方式

RestTemplate报错:no suitable HttpMessageConverter found for request type_第2张图片

 

找到原因所在,可以不使用RestTemplateBuilder创建对象来避免这个异常,为此对getInstance方法改造成以下的形式:

    public static RestTemplate getInstanceByCharset(String charset) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName(charset)));
        return restTemplate;
    }

后台不再报错,问题暂时解决,但不完美。这种写法无法解决中文乱码问题,且看另一篇文章 初探RestTemplate--解决中文乱码问题 ,文章末尾实现了一种可靠的构建RestTemplate方案。

 

你可能感兴趣的:(Java基础,java,异常,RestTemplate)