Spring Web Reactive | 2. WebClient | 2.4. Request Body

MonoやKotlinコルーチンのDeferredなど、ReactiveAdapterRegistryが扱う非同期型からリクエストボディをエンコードできます。

Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .body(personMono, Person.class)
        .retrieve()
        .bodyToMono(Void.class);

オブジェクトのストリームも同様にエンコードできます。実際の値がある場合はbodyValueを使用します。

Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(person)
        .retrieve()
        .bodyToMono(Void.class);

2.4.1. フォームデータ

ボディとしてMultiValueMap<String, String>を渡します。FormHttpMessageWriterapplication/x-www-form-urlencodedを自動設定します。

Mono<Void> result = client.post()
        .uri("/path", id)
        .bodyValue(formData)
        .retrieve()
        .bodyToMono(Void.class);

インラインのフォームデータにはBodyInsertersを使用します。

.body(fromFormData("k1", "v1").with("k2", "v2"))

2.4.2. マルチパートデータ

パート内容のオブジェクト、または内容とヘッダーを持つHttpEntityを値とするMultiValueMap<String, ?>を渡します。MultipartBodyBuilderは便利な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();

通常、パートのContent-Typeは選択されたHttpMessageWriterまたはResourceの拡張子から自動決定されます。必要な場合はオーバーロードされたpartメソッドでMediaTypeを指定します。

Mono<Void> result = client.post()
        .uri("/path", id)
        .body(builder.build())
        .retrieve()
        .bodyToMono(Void.class);

MultipartBodyBuilderを使用すると、HttpEntityラッパーによってマルチパートとして扱われます。BodyInsertersでインラインのマルチパート内容を渡すこともできます。

.body(fromMultipartData("fieldPart", "value").with("filePart", resource))