This is my first question here, I am a beginner in using the REST template and Spring and I apologize if I am asking simple questions.
I am trying to call a delete method from another component using the REST template. The response I receive in POSTMAN is the following JSON:
{
"code": 100,
"message": "my message"
}
I should not be able to delete the object, so my request fails with org.springframework.web.client.HttpClientErrorException.
In the logs all I see is the:
[Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause...
I have searched a bit and I have seen that when try to call a rest service with restTemplate, the body of response is lost if it returns a 400.
This is the code I have used to catch the HttpClientErrorException:
try{
restTemplate.delete(url);
}
catch (HttpClientErrorException e) {
LOG.error("FM HttpClientErrorException caught");
LOG.error("FM response body : {}", e.getResponseBodyAsString());
LOG.error("FM response headers message: {}", e.getResponseHeaders().toString());
LOG.error("FM response message : {}", e.getMessage());
LOG.error("FM response status : {}", e.getStatusCode());
}
I have seen in other posts DELETE in Spring RestTemplate with HttpEntity<List> that one solution is to catch the exception and try to get the body of the response.
However, in my case this is always empty.
I have tried getting the response as well using the exchange from restTemplate and then catching the Exception as above, but my body is still empty:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);
LOG.info("FM response body : {}", response.getBody());
LOG.info("FM response status : {}", response.getStatusCode());
Unit test result:
Unit tes2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - HttpClientErrorException caught
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response body : []
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response headers message: {}
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response message : 400 Bad Request
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response status : 400t results:
The questions are:
- Can we retrieve the JSON from the response using a REST delete call?
- Can we do the same using the exchange? If yes, how can we retrieve the JSON sent? I tried both and the body is always empty.
I have seen also this post: What is the HTTP status return code for a successful DELETE statement in REST? The 3rd question would be then:
- Is it a good practice to return a JSON and say why the delete cannot succeed?
Thank you very much, any help or suggestion regarding the code or the solution is appreciated.