发生错误时如何使用 RestTemplate 读取正文?
how to read body using RestTemplate in case of an error?
我正在使用 RestTemplate 与一个 REST 服务通信,我使用
restTemplate.postForEntity(uri, request, MyResponse.class);
} catch (HttpClientErrorException e)
然而,当有错误(4xx 或 5xx)时,REST 服务 returns 在 JSON 中的描述,但是 HttpClientErrorException.getResponseBodyAsString()
return为空。 RestTemplate(如果我尝试将响应检索为字符串),也没有 return 任何东西。
如果出错如何检索正文?
您可以通过 ResponseErrorHandler
. The ResponseErrorHandler
needs to be set for the RestTemplate
with the setErrorHandler
方法访问错误响应。
ResponseErrorHandler 通过两种方法提供响应
boolean hasError(ClientHttpResponse response) throws IOException;
void handleError(ClientHttpResponse response) throws IOException;
问题已发现,已在此处描述
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() 方法读取它。
我正在使用 RestTemplate 与一个 REST 服务通信,我使用
restTemplate.postForEntity(uri, request, MyResponse.class);
} catch (HttpClientErrorException e)
然而,当有错误(4xx 或 5xx)时,REST 服务 returns 在 JSON 中的描述,但是 HttpClientErrorException.getResponseBodyAsString() return为空。 RestTemplate(如果我尝试将响应检索为字符串),也没有 return 任何东西。
如果出错如何检索正文?
您可以通过 ResponseErrorHandler
. The ResponseErrorHandler
needs to be set for the RestTemplate
with the setErrorHandler
方法访问错误响应。
ResponseErrorHandler 通过两种方法提供响应
boolean hasError(ClientHttpResponse response) throws IOException;
void handleError(ClientHttpResponse response) throws IOException;
问题已发现,已在此处描述 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() 方法读取它。