'Get the customized Response JSON from 422 Unprocessable Entity

I have a Java Springboot microservice which calls a third-party API. For one of my test cases, the API returns 422 Unprocessable entity with a customized Response JSON Body

{
    "request_status": "error",
    "status": "error",
    "requested_url": "www.example.de",
    "url": "http://www.newexample.de/",
    "issue": "redirect",
    "recommendedUrl": true,
    "error_message": "The web address you entered redirects to another website."
}

I am unable to retrieve this response body in my microservice. My code is like below

try {
    HttpEntity<Input_Class> httpentity = new HttpEntity<Input_Class>(                      inputClassObj, headers);
    responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpentity,
         new ParameterizedTypeReference<Output_Class>() {});

} catch(RestClientException ue) {
     if (ue instanceof HttpStatusCodeException) {
         String errorResponse = ((HttpStatusCodeException) ue).getResponseBodyAsString();
         logger.info(errorResponse);
}

The errorResponse I could see in the log is

{
    "status": "ERROR",
    "errorMessage": "Unprocessable Entity"
}

Can someone let me know which Exception class I should use to get the response body sent by the API.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source