缘起
有的接口啊,明明返回是json数据,但是响应头里面指定的Content-Type 值却是 text/plain。那么这就导致我们通过RestTemplete请求的时候会报错
Could not extract response: no suitable HttpMessageConverter found for response typ
比如微信的请求openid的接口
解决方案
新建WxMappingJackson2HttpMessageConverter类
代码语言:txt复制public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
public WxMappingJackson2HttpMessageConverter(){
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.TEXT_PLAIN);
mediaTypes.add(MediaType.TEXT_HTML);
setSupportedMediaTypes(mediaTypes);
}
}
设置restTemplate的MessageConverters
代码语言:txt复制@Component
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
return restTemplate;
}
}
使用
代码语言:txt复制@RequiredArgsConstructor
public class UserController {
private final RestTemplate restTemplate;
}