java - RestTemplate - RestClientException - 无法提取响应

标签 java spring rest get resttemplate

我在 Spring 应用程序中使用 RestTemplate 与 API 交互。我正在执行 GET 请求并期待一些 JSON 响应。执行此操作的代码如下:

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

当我运行它时,它会在以下行中断:

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

我收到以下异常:

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

我是 RestTemplates 的新手,一般来说,我是通过 Java 与 REST API 进行交互的,因此我们将非常感谢任何解决此问题的帮助。

最佳答案

您需要指定您的消息转换器并绑定(bind)它:

  <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>

关于java - RestTemplate - RestClientException - 无法提取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25387716/

相关文章:

java - 清理搞砸了我的 Android 项目

java - 第 7 行 "yyy.jspf"中出现错误 : The type java. lang.CharSequence 无法解析。它是从所需的 .class 文件间接引用的

Spring 缓存与缓存管理器

java - FusionAuthClient 单例

java - 来自第三方 API 的模拟调用和响应

java - 如何验证字符串是否为 YYYYMMDD 格式?

java - 如何将 Joda Time DateTime 对象转换为 SQL Server 格式的字符串?

java - Spring MVC + Jackson-JsonView

rest - 如何使用红色连接到 REST api?

ruby-on-rails - REST 中的客户端服务器 API 模式(不可靠的网络用例)