Search code examples
javaspringerror-handlinghttp-postresttemplate

RestTemplate get body with ResourceAccessException


I'm sending API and receiving status code 400 with body I need to parse

When working with RestTemplate I failed to parse response:

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
}

Also With adding error handlers (default and specific) suggested I always get a ResourceAccessException which isn't catch by HttpClientErrorException and doesn't include body/headers data

How can I still get body/headers in that case? must I use alternatives to RestTemplate ?

Moreover, how can I return to context of request when I'm in caught exception inside handleError:

 public void handleError(ClientHttpResponse response) throws IOException {

Solution

  • The issue I was using interceptor which read my body already,

    Changed RestTemplate to using BufferingClientHttpRequestFactory I can now re-read my body

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

    Using this wrapper allows for multiple reads of the response body.