Spring Web Reactive | 2. WebClient | 2.4. Request Body
Encode a request body from any asynchronous type handled by ReactiveAdapterRegistry, such as Mono or Kotlin coroutine Deferred.
Mono<Void> result = client.post()
.uri("/persons/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.body(personMono, Person.class)
.retrieve()
.bodyToMono(Void.class);
Encode a stream of objects in the same way. For an actual value, use bodyValue.
Mono<Void> result = client.post()
.uri("/persons/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(person)
.retrieve()
.bodyToMono(Void.class);
2.4.1. Form Data
Provide MultiValueMap<String, String> as the body. FormHttpMessageWriter automatically sets the content type to application/x-www-form-urlencoded.
Mono<Void> result = client.post()
.uri("/path", id)
.bodyValue(formData)
.retrieve()
.bodyToMono(Void.class);
Use BodyInserters for inline form data.
.body(fromFormData("k1", "v1").with("k2", "v2"))
2.4.2. Multipart Data
Provide a MultiValueMap<String, ?> whose values are part content objects or HttpEntity instances containing part content and headers. MultipartBodyBuilder offers a convenient API.
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("fieldPart", "fieldValue");
builder.part("filePart1", new FileSystemResource("...logo.png"));
builder.part("jsonPart", new Person("Jason"));
builder.part("myPart", part);
MultiValueMap<String, HttpEntity<?>> parts = builder.build();
Part content types are usually selected automatically from the chosen HttpMessageWriter or a Resource file extension. Use an overloaded part method to set a MediaType explicitly when required.
Mono<Void> result = client.post()
.uri("/path", id)
.body(builder.build())
.retrieve()
.bodyToMono(Void.class);
When using MultipartBodyBuilder, the HttpEntity wrappers ensure multipart handling. You can also provide inline multipart content with BodyInserters.
.body(fromMultipartData("fieldPart", "value").with("filePart", resource))