1. 程式人生 > >使用RestTemplate:報錯Could not extract response: no suitable HttpMessageConverter found for response typ

使用RestTemplate:報錯Could not extract response: no suitable HttpMessageConverter found for response typ

專案中需要呼叫微信介面獲取access_token等一系列和微信介面相關的操作,我使用了Spring自帶的RestTemplate類來發送Get或Post請求,直接在Spring配置檔案中依賴注入

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

使用的時候直接

@Resource
private RestTemplate restTemplate;

結果在呼叫微信介面的時候出了異常

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 
nested exception is org.springframework.web.client.RestClientException:
Could not extract response: no suitable HttpMessageConverter found for response type [] and content type [text/plain;charset=UTF-8]] with root cause org.springframework.web.client.RestClientException:
Could not extract response: no suitable HttpMessageConverter found for response type [] and content type [text/plain;charset=UTF-8]

原因:微信介面文件雖說返回的是 Json 資料,但是同時返回的 Header 裡面的 Content-Type 值卻是 text/plain 。

最終結果就是導致 RestTemplate 把資料從 HttpResponse 轉換成 Object 的時候,找不到合適的 HttpMessageConverter 來轉換。

在報錯資訊中知道,不支援[text/plain;charset=UTF-8]型別,需要繼承 MappingJackson2HttpMessageConverter 並在構造過程中設定其支援的 MediaType 型別:

public class WxMappingJackson2HttpMessageConverter
extends MappingJackson2HttpMessageConverter { public WxMappingJackson2HttpMessageConverter(){ List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.TEXT_PLAIN); mediaTypes.add(MediaType.TEXT_HTML); setSupportedMediaTypes(mediaTypes)
; } }
public class RestTemplateUtil {
    public static RestTemplate getInstance() {
    	RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        return restTemplate;
    }
}

參考:很厲害的作者https://blog.csdn.net/kinginblue/article/details/52706155