Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a body with HTTP DELETE when using WebFlux?

I want to access an HTTP API which provides a DELETE endpoint. This particular endpoint expects a list of items (which I want to delete) as JSON body.

Now, my problem is, I'm using Spring Webflux. But its WebClient doesn't give me the possibility, to send a body with a DELETE request. For a POST, I'd do this:

webClient.post()
         .uri("/foo/bar")
         .body(...)
         .exchange()

But for DELETE, I get a RequestHeadersSpec which doesn't give me the option to provide a body(...):

webClient.delete()
         .uri("/foo/bar")
         .body(...)       <--- METHOD DOES NOT EXIST
         .exchange()

So, what's the way to achieve this with Spring Webflux on the client side?

like image 254
Ethan Leroy Avatar asked Feb 20 '20 15:02

Ethan Leroy


People also ask

Can we send body in HTTP delete request?

If a DELETE request includes an entity body, the body is ignored [...] Additionally here is what RFC2616 (HTTP 1.1) has to say in regard to requests: an entity-body is only present when a message-body is present (section 7.2)


Video Answer


2 Answers

You can use webClient's method() operator. Simple example,

return webClient
        .method(HttpMethod.DELETE)
        .uri("/delete")
        .body(BodyInserters.fromProducer(Mono.just(new JSONObject().put("body","stringBody").toString()), String.class))
        .exchange() 
like image 146
Nipuna Saranga Avatar answered Oct 02 '22 08:10

Nipuna Saranga


  return webClient
            .method(HttpMethod.DELETE)
            .uri(url)
            .body(Mono.just(request), requestClass)
            .retrieve() 
            .toEntity(Void.class);

As result, we will get:

 Mono<ResponseEntity<Void>>
like image 31
Alexandr Kovalenko Avatar answered Oct 02 '22 10:10

Alexandr Kovalenko