12.4.2 Sending resources
Sending data with WebClient isn’t much different from receiving data. As an example, let’s say that you have a Mono<Ingredient> and want to send a POST request with the Ingredient that’s published by the Mono to the URI with a relative path of /ingredients. All you must do is use the post() method instead of get() and specify that the Mono is to be used to populate the request body by calling body() as follows:
Mono<Ingredient> ingredientMono = Mono.just(
new Ingredient("INGC", "Ingredient C", Ingredient.Type.VEGGIES));
Mono<Ingredient> result = webClient
.post()
.uri("/ingredients")
.body(ingredientMono, Ingredient.class)
.retrieve()
.bodyToMono(Ingredient.class);
result.subscribe(i -> { ... });If you don’t have a Mono or Flux to send, but instead have the raw domain object on hand, you can use bodyValue(). For example, suppose that instead of a Mono <Ingredient>, you have an Ingredient that you want to send in the request body, as shown next:
IIngedient ingredient = ...;
Mono<Ingredient> result = webClient
.post()
.uri("/ingredients")
.bodyValue(ingredient)
.retrieve()
.bodyToMono(Ingredient.class);
result.subscribe(i -> { ... });Instead of a POST request, if you want to update an Ingredient with a PUT request, you call put() instead of post() and adjust the URI path accordingly, like so:
Mono<Void> result = webClient
.put()
.uri("/ingredients/{id}", ingredient.getId())
.bodyValue(ingredient)
.retrieve()
.bodyToMono(Void.class);
result.subscribe();PUT requests typically have empty response payloads, so you must ask bodyToMono() to return a Mono of type Void. On subscribing to that Mono, the request will be sent.
