[英]how to read body using RestTemplate in case of an error?
I'm using RestTemplate to communicate with one REST service, i use 我正在使用RestTemplate与一种REST服务通信,我使用
restTemplate.postForEntity(uri, request, MyResponse.class);
} catch (HttpClientErrorException e)
however when there is an error (4xx or 5xx) REST service returns description in JSON in a body, but HttpClientErrorException.getResponseBodyAsString() returns null. 但是,当出现错误(4xx或5xx)时,REST服务在主体中以JSON形式返回描述,但是HttpClientErrorException.getResponseBodyAsString()返回null。 RestTemplate (if i try to retrieve response as String), doesn't return anything as well. RestTemplate(如果我尝试将响应检索为String),则不会返回任何内容。
How to retrieve body in case of error? 出现错误时如何取回尸体?
You can access the response for errors via a ResponseErrorHandler
. 您可以通过ResponseErrorHandler
访问响应以获取错误。 The ResponseErrorHandler
needs to be set for the RestTemplate
with the setErrorHandler
method. 需要使用setErrorHandler
方法为RestTemplate
设置ResponseErrorHandler
。
The ResponseErrorHandler provides the response via the two methods ResponseErrorHandler通过两种方法提供响应
boolean hasError(ClientHttpResponse response) throws IOException; boolean hasError(ClientHttpResponse response)抛出IOException;
void handleError(ClientHttpResponse response) throws IOException; void handleError(ClientHttpResponse response)引发IOException;
Problem was recognised, it's described here https://jira.spring.io/browse/SPR-16781?focusedCommentId=159473&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-159473 and here https://jira.spring.io/browse/SPR-9367 问题已被识别,在此处进行了描述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
you need to use different http library, for example Apache HttpClient (not a default one from JDK). 您需要使用其他http库,例如Apache HttpClient(不是JDK的默认库)。
Add to your project: 添加到您的项目:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
and configure RestTemplate with: 并使用以下命令配置RestTemplate:
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
you can use ResponseErrorHandler if you need, but it's not necessary. 您可以根据需要使用ResponseErrorHandler ,但这不是必需的。
Now response body (even in error situation) is stored in HttpClientErrorException , read it with getResponseBodyAsString() method. 现在,响应主体(即使处于错误情况下)也存储在HttpClientErrorException中 ,并使用getResponseBodyAsString()方法读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.