使用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'

猜你喜欢

转载自blog.csdn.net/qq_36865108/article/details/85293756
今日推荐