Could not extract response: no suitable HttpMessageConverter found for content type [xxx]
时间: 2023-11-21 11:57:25 浏览: 188
当我们使用Spring RestTemplate进行HTTP请求时,有时会遇到"Could not extract response: no suitable HttpMessageConverter found for content type [xxx]"的错误。这是因为RestTemplate默认使用的HttpMessageConverter无法处理返回的数据类型。解决这个问题的方法是添加一个能够处理该数据类型的HttpMessageConverter。
以下是两种解决方法:
1.使用MappingJackson2HttpMessageConverter
```java
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.valueOf("application/vnd.github.v3+json")));
restTemplate.getMessageConverters().add(converter);
```
2.自定义HttpMessageConverter
```java
public class MyHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public MyHttpMessageConverter() {
super(MediaType.valueOf("application/vnd.github.v3+json"));
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
// 处理返回的数据
return null;
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
// 处理发送的数据
}
}
```
然后将自定义的HttpMessageConverter添加到RestTemplate中:
```java
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MyHttpMessageConverter());
```
阅读全文