2

I'm making a call to a Magento REST service which returns a message if there was an error. For a 401 error the response body should be {"message":"You did not sign in correctly or your account is temporarily disabled."}). Using RestTemplate how do I get to the body?

public GetTokenResponse call(String url, GetTokenRequest request)
{
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<GetTokenResponse> result = restTemplate.postForEntity(url, request, GetTokenResponse.class);
        // throws RestClientException on 401 error
        return result.getBody();
    } catch (HttpClientErrorException e) {
        // responseBody shows empty
        throw new UnrecoverableException(e);
    }
}

I know that there is a response body present in the payload coming back from the server. Here is the response body I pulled from WireShark: enter image description here

Edit: When I call a method that gets a 400 error the body is populated correctly so this appears to be limited to certain statuses?

BHarman
  • 572
  • 1
  • 6
  • 15
  • Note that the exception in the linked duplicate also exposes the response body. – Sotirios Delimanolis Jul 29 '16 at 15:25
  • There is a method to get the response body but it is just an empty byte array. – BHarman Jul 29 '16 at 15:30
  • Then I'm doubtful of the body in the response. Looking at the source code of `RestTemplate`, it only ever creates a `HttpClientErrorException` with the constructor that accepts a body argument. Try to use `RestTemplate#setErrorHandler` with a custom `ResponseErrorHandler` and see what's available there. – Sotirios Delimanolis Jul 29 '16 at 15:32
  • I can curl the endpoint and see the response body. That's where `{"message":"You did not sign in correctly or your account is temporarily disabled."}` came from. – BHarman Jul 29 '16 at 15:37
  • What version of the library are you using? – Sotirios Delimanolis Jul 29 '16 at 15:38
  • I've tried 3.1.1 and 4.3.1 – BHarman Jul 29 '16 at 15:38
  • `HttpClientErrorException#getResponseBodyAsByteArray` works fine for me. Is the URL you're testing public? – Sotirios Delimanolis Jul 29 '16 at 15:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118650/discussion-between-brian-harman-and-sotirios-delimanolis). – BHarman Jul 29 '16 at 15:43
  • The issue isn't really Spring. It's `HttpURLConnection` which `RestTemplate` uses by default. It's set up to use some kind of streaming mode which your web server rejects. – Sotirios Delimanolis Jul 29 '16 at 17:47
  • 1
    Use a different HTTP client like Apache's Http Components with `restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());` (or Netty, or OkHttp, or whatever other HTTP library) and you'll get the body you expected. – Sotirios Delimanolis Jul 29 '16 at 17:47
  • Check the duplicated question : https://stackoverflow.com/a/54986825/3957754 – JRichardsz Mar 04 '19 at 15:59

0 Answers0