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<String, Object>来封装参数,但是无法找到合适的类型转换,仔细查看我的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接口)

 

 

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

 

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

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

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

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alphathur

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值