Java : HttpRequest.BodyPublishers with Examples

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


Summary

Implementations of BodyPublisher that implement various useful publishers, such as publishing the request body from a String, or from a file.

Class diagram

Code examples on this page may use node.js as the test server.

// server-post.js

const http = require('http');
const server = http.createServer((req, res) => {

  if (req.method == 'POST') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk;
    });
    req.on('end', () => {
      console.log('body : ' + body);
      res.end();
    });
  }

});

server.listen(8001);
final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.ofString("post text");

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : post text

Methods

static HttpRequest.BodyPublisher concat (HttpRequest.BodyPublisher... publishers)

Returns a BodyPublisher that publishes a request body consisting of the concatenation of the request bodies published by a sequence of publishers.

final var uri = URI.create("http://127.0.0.1:8001/");

final var body1 = HttpRequest.BodyPublishers.ofString("abcd");
final var body2 = HttpRequest.BodyPublishers.ofString("XYZ");
final var concatenatedBody = HttpRequest.BodyPublishers.concat(body1, body2);

final var request = HttpRequest.newBuilder(uri)
        .POST(concatenatedBody)
        .header("Content-Type", "text/plain; charset=UTF-8")
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcdXYZ

static HttpRequest.BodyPublisher fromPublisher (Flow.Publisher<? extends ByteBuffer> publisher)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher.

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, "abcd");

try (final var is = Files.newInputStream(path)) {

    final var uri = URI.create("http://127.0.0.1:8001/");

    final var publisher = HttpRequest.BodyPublishers.ofInputStream(() -> is);
    final var body = HttpRequest.BodyPublishers.fromPublisher(publisher);

    final var request = HttpRequest.newBuilder(uri)
            .POST(body)
            .header("Content-Type", "text/plain; charset=UTF-8")
            .build();
    System.out.println(request); // http://127.0.0.1:8001/ POST

    try (final var client = HttpClient.newHttpClient()) {
        final var response = client.send(
                request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response); // (POST http://127.0.0.1:8001/) 200
    }
}

// -- node.js --
//$ node server-post.js
//body : abcd

static HttpRequest.BodyPublisher fromPublisher (Flow.Publisher<? extends ByteBuffer> publisher, long contentLength)

Returns a request body publisher whose body is retrieved from the given Flow.Publisher.

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, "abcd");
final var length = Files.size(path);

try (final var is = Files.newInputStream(path)) {

    final var uri = URI.create("http://127.0.0.1:8001/");

    final var publisher = HttpRequest.BodyPublishers.ofInputStream(() -> is);
    final var body = HttpRequest.BodyPublishers.fromPublisher(publisher, length);

    final var request = HttpRequest.newBuilder(uri)
            .POST(body)
            .header("Content-Type", "text/plain; charset=UTF-8")
            .build();
    System.out.println(request); // http://127.0.0.1:8001/ POST

    try (final var client = HttpClient.newHttpClient()) {
        final var response = client.send(
                request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response); // (POST http://127.0.0.1:8001/) 200
    }
}

// -- node.js --
//$ node server-post.js
//body : abcd

static HttpRequest.BodyPublisher noBody ()

A request body publisher which sends no request body.

final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.noBody();

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body :

static HttpRequest.BodyPublisher ofByteArray (byte[] buf)

Returns a request body publisher whose body is the given byte array.

final var uri = URI.create("http://127.0.0.1:8001/");

final byte[] buf = "abcd".getBytes();
System.out.println(Arrays.toString(buf)); // [97, 98, 99, 100]

final var body = HttpRequest.BodyPublishers.ofByteArray(buf);
final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcd

static HttpRequest.BodyPublisher ofByteArray (byte[] buf, int offset, int length)

Returns a request body publisher whose body is the content of the given byte array of length bytes starting from the specified offset.

final var uri = URI.create("http://127.0.0.1:8001/");

final byte[] buf = "abcdef".getBytes();
System.out.println(Arrays.toString(buf)); // [97, 98, 99, 100, 101, 102]

final var body = HttpRequest.BodyPublishers.ofByteArray(buf, 2, 3);
final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : cde

static HttpRequest.BodyPublisher ofByteArrays (Iterable<byte[]> iter)

A request body publisher that takes data from an Iterable of byte arrays.

final var uri = URI.create("http://127.0.0.1:8001/");

final byte[] buf1 = "ab".getBytes();
final byte[] buf2 = "cd".getBytes();
final byte[] buf3 = "efg".getBytes();

System.out.println(Arrays.toString(buf1)); // [97, 98]
System.out.println(Arrays.toString(buf2)); // [99, 100]
System.out.println(Arrays.toString(buf3)); // [101, 102, 103]

final var iter = List.of(buf1, buf2, buf3);
final var body = HttpRequest.BodyPublishers.ofByteArrays(iter);

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcdefg

static HttpRequest.BodyPublisher ofFile (Path path)

A request body publisher that takes data from the contents of a File.

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, "abcd");

final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.ofFile(path);

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .header("Content-Type", "text/plain; charset=UTF-8")
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcd

static HttpRequest.BodyPublisher ofInputStream (Supplier<? extends InputStream> streamSupplier)

A request body publisher that reads its data from an InputStream.

final Supplier<InputStream> streamSupplier = () -> {
    final byte[] buf = "abcd".getBytes();
    return new ByteArrayInputStream(buf);
};

final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.ofInputStream(streamSupplier);

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcd

static HttpRequest.BodyPublisher ofString (String body)

Returns a request body publisher whose body is the given String, converted using the UTF_8 character set.

final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.ofString("post text");

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : post text

static HttpRequest.BodyPublisher ofString (String s, Charset charset)

Returns a request body publisher whose body is the given String, converted using the given character set.

final var uri = URI.create("http://127.0.0.1:8001/");
final var body = HttpRequest.BodyPublishers.ofString(
        "abcd", StandardCharsets.US_ASCII);

final var request = HttpRequest.newBuilder(uri)
        .POST(body)
        .header("Content-Type", "text/plain; charset=US-ASCII")
        .build();
System.out.println(request); // http://127.0.0.1:8001/ POST

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}

// -- node.js --
//$ node server-post.js
//body : abcd

Related posts

To top of page