【问题标题】:how to read body using RestTemplate in case of an error?出现错误时如何使用 RestTemplate 读取正文?
【发布时间】:2018-12-14 16:24:11
【问题描述】:

我正在使用 RestTemplate 与一个 REST 服务进行通信,我使用

     restTemplate.postForEntity(uri, request, MyResponse.class);
 } catch (HttpClientErrorException e)

但是,当出现错误(4xx 或 5xx)时,REST 服务会在正文中返回 JSON 描述,但 HttpClientErrorException.getResponseBodyAsString() 返回空值。 RestTemplate(如果我尝试以字符串形式检索响应),也不返回任何内容。

发生错误时如何检索正文?

【问题讨论】:

  • 你是如何创建restTemplate的?

标签: java spring resttemplate spring-rest


【解决方案1】:

您可以通过ResponseErrorHandler 访问错误响应。需要使用setErrorHandler 方法为RestTemplate 设置ResponseErrorHandler

ResponseErrorHandler 通过两种方法提供响应

boolean hasError(ClientHttpResponse response) throws IOException;

void handleError(ClientHttpResponse response) 抛出 IOException;

【讨论】:

  • 您可以访问错误代码(但您可以从异常中读取它们),但您无法访问响应正文。
【解决方案2】:

问题已被识别,在此处进行了描述 https://jira.spring.io/browse/SPR-16781?focusedCommentId=159473&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-159473 和这里 https://jira.spring.io/browse/SPR-9367

您需要使用不同的 http 库,例如 Apache HttpClient(不是 JDK 的默认库)。

添加到您的项目中:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

并使用以下命令配置 RestTemplate:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

如果需要,您可以使用 ResponseErrorHandler,但这不是必需的。

现在响应正文(即使在错误情况下)存储在 HttpClientErrorException 中,使用 getResponseBodyAsString() 方法读取它。

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2023-03-03
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多