【送信側】Content-Length と chunked の使い分け
1.Content-Length を明示的に使いたい場合
WebClientは、body()の内容がメモリ上に展開可能である場合、自動的にContent-Lengthを付与します
String payload = "固定サイズのリクエスト";
client.post()
.uri("http://example.com/api")
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(payload.getBytes(StandardCharsets.UTF_8).length))
.bodyValue(payload)
.retrieve()
.bodyToMono(String.class)
.subscribe(System.out::println);
上記のように、bodyValue を使うと Content-Length を自動設定してくれます。明示的に header() を使っても構いませんが、省略可能です。
2.Transfer-Encoding: chunked にしたい場合
FluxやDataBufferのようなストリーミング送信では chunked になります。以下のように Flux を使うと、Content-Length は付かず、自動的に Transfer-Encoding: chunked が設定されます。
Flux<String> flux = Flux.just("chunk1", "chunk2", "chunk3");
client.post()
.uri("http://example.com/stream")
.body(BodyInserters.fromPublisher(flux, String.class))
.retrieve()
.bodyToMono(String.class)
.subscribe(System.out::println);
【受信側】どちらにも対応するには?
WebClientは受信時に Content-Length でも chunked でも 自動的に判別してくれます。特に追加設定は不要です。
client.get()
.uri("http://example.com/data")
.retrieve()
.bodyToMono(String.class)
.subscribe(System.out::println);