繁体   English   中英

出现错误时如何使用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服务在主体中以JSON形式返回描述,但是HttpClientErrorException.getResponseBodyAsString()返回null。 RestTemplate(如果我尝试将响应检索为String),则不会返回任何内容。

出现错误时如何取回尸体?

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

ResponseErrorHandler通过两种方法提供响应

boolean hasError(ClientHttpResponse response)抛出IOException;

void handleError(ClientHttpResponse response)引发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()方法读取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM