Search code examples
javaspringresttemplatespring-rest

how to read body using RestTemplate in case of an error?


I'm using RestTemplate to communicate with one REST service, i use

     restTemplate.postForEntity(uri, request, MyResponse.class);
 } catch (HttpClientErrorException e)

however when there is an error (4xx or 5xx) REST service returns description in JSON in a body, but HttpClientErrorException.getResponseBodyAsString() returns null. RestTemplate (if i try to retrieve response as String), doesn't return anything as well.

How to retrieve body in case of error?


Solution

  • Problem was recognised, it's described here https://jira.spring.io/browse/SPR-16781?focusedCommentId=159473&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-159473 and here https://jira.spring.io/browse/SPR-9367

    you need to use different http library, for example Apache HttpClient (not a default one from JDK).

    Add to your project:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>
    

    and configure RestTemplate with:

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    

    you can use ResponseErrorHandler if you need, but it's not necessary.

    Now response body (even in error situation) is stored in HttpClientErrorException, read it with getResponseBodyAsString() method.