使用Spring-RestTemplate时出现RestClientException的解决办法

错误解释

出现这个错误有两个不同的原因:

  1. 你所访问的API的服务器的响应类型是text/html,而restTemplate不能将这种类型转换成你要求的类的结构
  2. 如果响应类型就是application/json,那么就是缺少一个jackson的依赖

解决

  1. 第一种原因的解决办法是为RestTemplate实例添加自定义消息转换器,接收所有响应类型.下面是代码.
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
       //Add the Jackson Message converter
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        // Note: here we are making this converter to process any kind of response,
        // not only application/*json, which is the default behaviour
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
        messageConverters.add(converter);
        restTemplate.setMessageConverters(messageConverters);

关键就是这句
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
表示支持所有类型

  1. 第二种很简单,就是引入一个依赖
    maven :
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>

Gradle:

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.7'

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值