【问题标题】:RestTemplate get body with ResourceAccessExceptionRestTemplate 使用 ResourceAccessException 获取正文
【发布时间】:2019-07-31 05:48:12
【问题描述】:

我正在发送 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 {

【问题讨论】:

    标签: java spring error-handling http-post resttemplate


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2014-12-02
      • 2020-09-30
      • 2013-07-08
      • 2016-07-22
      • 2017-12-31
      • 2013-05-22
      • 2016-08-22
      • 1970-01-01
      相关资源
      最近更新 更多