0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring WebClient(reactor-netty)Transfer-Encoding: chunked だけでなく Content-Length にも対応させたい

Posted at

【送信側】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);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?