DELETE in Spring RestTemplate with HttpEntity<List>

22,680

From the comments it became clear that you're expecting it to return a 400 Bad Request response. RestTemplate will see these as "client errors" and it will throw a HttpClientErrorException.

If you want to handle cases like this, you should catch this exception, for example:

try {
    ResponseEntity<String> responseMS  = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
} catch (HttpClientErrorException ex) {
    String message = ex.getResponseBodyAsString();
}

In this case (since you expect a String), you can use the getResponseBodyAsString() method.


The ResponseEntity will only contain the data in case your request can be executed successfully (2xx status code, like 200, 204, ...). So, if you only expect a message to be returned if the request was not successfully, you can actually do what Mouad mentioned in the comments and you can use the delete() method of the RestTemplate.

Share:
22,680

Related videos on Youtube

Miguel Carrasco
Author by

Miguel Carrasco

Updated on February 28, 2020

Comments

  • Miguel Carrasco
    Miguel Carrasco about 4 years

    I don't know why my code is not working, I've tried with Postman and works fine:

    WORKS FINE

    But with RestTemplate I can´t get a response while it´s using the same endpoint... .

    ResponseEntity<String> responseMS  = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
    

    I've tried with List instead Array[]

    When i made a PUT request it´s works fine but with one object:

    ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);
    

    Any help?? Thanks!!

    • g00glen00b
      g00glen00b about 7 years
      @MouadELFakir restTemplate.exchange() should also work. The delete() API does not allow you to send a request body as far as I know.
  • LazR
    LazR about 5 years
    Thanks for your answer! Just as an update TestRestTemplate.delete(...) is still void ... I don't understand why is there no deleteForEntity as for all the other HttpMethods, just with response.body = null
  • Michael Coxon
    Michael Coxon over 4 years
    Actually, the same seems to be true for RestTemplate.patch(...) as well