Java : HttpRequest.BodyPublishers (HTTP通信) - API使用例

HttpRequest.BodyPublishers (Java SE 18 & JDK 18) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。


概要

Stringからのリクエスト本文の公開やファイルからの公開など、各種の便利なパブリッシャを実装するBodyPublisherの実装。

クラス構成

HttpRequest.BodyPublishers は HttpRequest.BodyPublisher を作成するためのクラスです。
BodyPublisher は HttpRequest のボディ(リクエスト本文)を表します。

final var uri = URI.create("http://example.com/");
final var body = HttpRequest.BodyPublishers.ofString("some body text");

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 14\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 231697]
//    File Data: 14 bytes
//Line-based text data: text/plain (1 lines)
//    some body text

メソッド

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

パブリッシャのシーケンスによってパブリッシュされたリクエスト本文の連結で構成されるリクエスト本文をパブリッシュするBodyPublisherを返します。

final var uri = URI.create("http://example.com/");

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://example.com/ POST

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 7\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 237675]
//    File Data: 7 bytes
//Line-based text data: text/plain (1 lines)
//    abcdXYZ

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

指定されたFlow.Publisherから本文が取得されたリクエスト・ボディ・パブリッシャを返します。

関連:fromPublisher(Flow.Publisher<? extends ByteBuffer> publisher, long contentLength)

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://example.com/");

    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://example.com/ POST

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

    System.out.println(response); // (POST http://example.com/) 200
}

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Transfer-encoding: chunked\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 541422]
//    HTTP chunked response
//    File Data: 4 bytes
//Line-based text data: text/plain (1 lines)
//    abcd

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

指定された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://example.com/");

    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://example.com/ POST

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

    System.out.println(response); // (POST http://example.com/) 200
}

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 4\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 550491]
//    File Data: 4 bytes
//Line-based text data: text/plain (1 lines)
//    abcd

static HttpRequest.BodyPublisher noBody ()

リクエスト本文を送信しないリクエストボディ・パブリッシャ。

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

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 0\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 212953]

static HttpRequest.BodyPublisher ofByteArray (byte[] buf)

本文が指定されたバイト配列であるリクエストボディ・パブリッシャを返します。

final var uri = URI.create("http://example.com/");

final byte[] buf = {0x10, 0x20, 0x30};
final var body = HttpRequest.BodyPublishers.ofByteArray(buf);

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 3\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 211657]
//    File Data: 3 bytes
//    Data (3 bytes)
//        Data: 102030
//        [Length: 3]

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

指定されたoffsetから始まるlengthバイトの指定されたバイト配列の内容を本文として持つリクエストボディ・パブリッシャを返します。

final var uri = URI.create("http://example.com/");

final byte[] buf = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60};
final var body = HttpRequest.BodyPublishers.ofByteArray(buf, 2, 3);

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 3\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 210142]
//    File Data: 3 bytes
//    Data (3 bytes)
//        Data: 304050
//        [Length: 3]

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

バイト配列のIterableからデータを取得するリクエストボディ・パブリッシャ。

final var uri = URI.create("http://example.com/");

final byte[] buf1 = {0x10, 0x20};
final byte[] buf2 = {0x30, 0x40};
final byte[] buf3 = {0x50, 0x60, 0x70};

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://example.com/ POST

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Transfer-encoding: chunked\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 202134]
//    HTTP chunked response
//    File Data: 7 bytes
//    Data (7 bytes)
//        Data: 10203040506070
//        [Length: 7]

static HttpRequest.BodyPublisher ofFile (Path path)

ファイルの内容からデータを取得するリクエスト・ボディ・パブリッシャ。

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://example.com/");
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://example.com/ POST

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 4\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 254805]
//    File Data: 4 bytes
//Line-based text data: text/plain (1 lines)
//    abcd

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

InputStreamからデータを読み取るリクエスト・ボディ・パブリッシャ。

final Supplier<InputStream> streamSupplier = () -> {
    final byte[] buf = {0x10, 0x20, 0x30};
    return new ByteArrayInputStream(buf);
};

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

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Transfer-encoding: chunked\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 258176]
//    HTTP chunked response
//    File Data: 3 bytes
//    Data (3 bytes)
//        Data: 102030
//        [Length: 3]

static HttpRequest.BodyPublisher ofString (String body)

UTF_8文字セットを使用して変換された、指定された Stringの本文を持つリクエスト本体パブリッシャを返します。

final var uri = URI.create("http://example.com/");
final var body = HttpRequest.BodyPublishers.ofString("abcd");

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 4\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=UTF-8\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 265145]
//    File Data: 4 bytes
//Line-based text data: text/plain (1 lines)
//    abcd

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

指定された文字セットを使用して変換された、指定された Stringの本文を持つリクエスト・ボディ・パブリッシャを返します。

final var uri = URI.create("http://example.com/");
final var body = HttpRequest.BodyPublishers.ofString("abcd", Charset.forName("Shift_JIS"));

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

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

System.out.println(response); // (POST http://example.com/) 200

// -- ネットワークログ --
//Hypertext Transfer Protocol
//    POST / HTTP/1.1\r\n
//    Connection: Upgrade, HTTP2-Settings\r\n
//    Content-Length: 4\r\n
//    Host: example.com\r\n
//    HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA\r\n
//    Upgrade: h2c\r\n
//    User-Agent: Java-http-client/18.0.1.1\r\n
//    Content-Type: text/plain; charset=Shift_JIS\r\n
//    \r\n
//    [Full request URI: http://example.com/]
//    [HTTP request 1/1]
//    [Response in frame: 272014]
//    File Data: 4 bytes
//Line-based text data: text/plain (1 lines)
//    abcd

関連記事

ページの先頭へ