首页 > 解决方案 > RestTemplate 使用 ResourceAccessException 获取正文

问题描述

我正在发送 API 并接收带有我需要解析的正文的状态代码 400

使用RestTemplate时,我无法解析响应:

try {
     ResponseEntity<ResponseVO> response = restTemplate.exchange(uri, HttpMethod.POST, request, ResponseVO.class);
} catch(HttpStatusCodeException e){
     // not catch
     String errorpayload = e.getResponseBodyAsString();
}  catch (RestClientException e) {  
    // catch without body
}

还建议添加错误处理程序(默认和特定),我总是得到一个ResourceAccessException未被捕获HttpClientErrorException且不包含正文/标题数据的

在这种情况下,我怎样才能获得正文/标题?我必须使用 RestTemplate 的替代品吗?

此外,当我在内部捕获异常时,如何返回请求上下文handleError

 public void handleError(ClientHttpResponse response) throws IOException {

标签: javaspringerror-handlinghttp-postresttemplate

解决方案


我使用的拦截器已经读取了我的身体的问题,

将 RestTemplate 更改为使用BufferingClientHttpRequestFactory我现在可以重新读取我的正文

RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));

使用此包装器允许多次读取响应正文。


推荐阅读