我正在使用RestTemplate与一个REST服务进行通信
restTemplate.postForEntity(uri, request, MyResponse.class);
} catch (HttpClientErrorException e)
但是,当发生错误(4xx或5xx)时,REST服务会在主体中以JSON返回描述,但是HttpClientErrorException.getResponseBodyAsString() 返回null。 RestTemplate(如果我尝试将响应检索为String),也不会返回任何内容。
在出现错误的情况下如何取回尸体?
答案 0 :(得分:1)
发现问题,在此进行描述 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()方法读取它。
答案 1 :(得分:0)
您可以通过ResponseErrorHandler
访问错误响应。需要使用setErrorHandler
方法为ResponseErrorHandler
设置RestTemplate
。
ResponseErrorHandler通过两种方法提供响应
boolean hasError(ClientHttpResponse response)引发IOException;
void handleError(ClientHttpResponse response)引发IOException;