Issue
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.
Solution
catch(RestClientException ue) {
if (ue instanceof HttpStatusCodeException) {
String errorResponse = ((HttpStatusCodeException) ue).getResponseBodyAsString();
logger.info(errorResponse);
}
This code block actually works. errorResponse returns the response JSON. I was using another endpoint url which was wrapping up the response & therefore, did not get the actual response.
Answered By - Uma Ilango
Answer Checked By - Mildred Charles (JavaFixing Admin)