我正在使用 RestTemplate 与一个 REST 服务进行通信,我使用
restTemplate.postForEntity(uri, request, MyResponse.class);
} catch (HttpClientErrorException e)
但是,当出现错误(4xx 或 5xx)时,REST 服务会在正文中返回 JSON 格式的描述,但 HttpClientErrorException.getResponseBodyAsString() 返回空值。 RestTemplate(如果我尝试以字符串形式检索响应),也不会返回任何内容。
发生错误时如何检索正文?
最佳答案
您可以通过 ResponseErrorHandler
访问错误响应。需要使用 setErrorHandler
为 RestTemplate
设置 ResponseErrorHandler
方法。
ResponseErrorHandler 通过两种方法提供响应
boolean hasError(ClientHttpResponse response) throws IOException;
void handleError(ClientHttpResponse response) throws IOException;
关于java - 发生错误时如何使用 RestTemplate 读取正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783465/