RestTemplate - RestClientException - Could Not Ext

2019-09-10 09:18发布

问题:

I am using RestTemplate in my Spring application to interact with an API. I am doing a GET request and expecting some JSON in response. The code to do this is as follows:

HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(null, requestHeaders);
ResponseEntity responseLogin = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyResponse.class);

When I run this its breaks on the following line:

ResponseEntity responseLogin = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyResponse.class);

I get the following exception:

Could not extract response: no suitable HttpMessageConverter found for response type [com.responses.MyResponse] and content type [application/json;charset=utf-8]

I'm new to RestTemplates and interacting with REST API with Java in general, so any help in solving this problem will be highly appreciated.

回答1:

You need to specify your messageconverter and bind it:

  <mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
            <property name="supportedMediaTypes">
                <list>
                    <bean class="org.springframework.http.MediaType">
                        <constructor-arg index="0" value="application" />
                        <constructor-arg index="1" value="json" />
                        <constructor-arg index="2" value="UTF-8" />
                    </bean>
                </list>
            </property>

        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>