Java : HttpRequest.BodyPublisher with Examples

HttpRequest.BodyPublisher (Java SE 21 & JDK 21) with Examples.
You will find code examples on most HttpRequest.BodyPublisher methods.


Summary

A BodyPublisher converts high-level Java objects into a flow of byte buffers suitable for sending as a request body. The class BodyPublishers provides implementations of many common publishers.

Class diagram

final var body = HttpRequest.BodyPublishers.ofString("abc XYZ 123");
System.out.println(body.contentLength()); // 11

final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .header("Content-Type", "text/plain; charset=UTF-8")
        .build();
System.out.println(request); // https://example.com/ POST

Methods

long contentLength ()

Returns the content length for this request body.

final var body = HttpRequest.BodyPublishers.ofString("abc XYZ 123");
System.out.println(body.contentLength()); // 11
final var body = HttpRequest.BodyPublishers.noBody();
System.out.println(body.contentLength()); // 0

Methods declared in Flow.Publisher

subscribe

Please see the link below.


Related posts

To top of page