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

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


概要

HTTPリクエスト。

クラス構成

HttpRequest は HTTP通信の要求を表すクラスです。

  • 要求先の URI
  • GET や POST などのリクエスト・メソッド
  • タイムアウト時間

などの属性を持ちます。

補足

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

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

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

System.out.println(response); // (GET http://127.0.0.1:8000/) 200
System.out.println(response.body()); // abcd

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe -o verbose
//Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
//Serving R:\java-work and subdirectories on 127.0.0.1 port 8000
//URL http://127.0.0.1:8000/
//127.0.0.1 - - [24/Jul/2022:15:15:18 +0900] "GET / HTTP/1.1" 200 -
//Resource requested: R:\java-work
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> User-agent: Java-http-client/18.0.1.1
//> Upgrade: h2c
//> Content-length: 0
//>
//< Date: Sun, 24 Jul 2022 06:15:18 GMT
//< Last-modified: Sun, 24 Jul 2022 04:58:24 GMT
//< Content-type: text/html
//< Content-length: 6
//<

コンストラクタ

HttpRequest ()

HttpRequestを作成します。

protectedです。
独自にサブクラスを作ることは少ないと思いますので、コード例は割愛します。

メソッド

abstract Optional<HttpRequest.BodyPublisher> bodyPublisher ()

このリクエストで設定されたHttpRequest.BodyPublisherを含むOptionalを返します。

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

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

request.bodyPublisher().ifPresent(a -> {
    System.out.println(a.equals(bodyPublisher)); // true
});

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

System.out.println(response); // (POST http://127.0.0.1:8000/) 405

// -- jwebserver --
//127.0.0.1 - - [24/Jul/2022:17:00:16 +0900] "POST / HTTP/1.1" 405 -
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> Upgrade: h2c
//> User-agent: Java-http-client/18.0.1.1
//> Content-length: 14
//>
//< Date: Sun, 24 Jul 2022 08:00:16 GMT
//< Allow: HEAD, GET
//< Content-length: 0

// -- ネットワークログ --
//POST / HTTP/1.1
//Connection: Upgrade, HTTP2-Settings
//Content-Length: 14
//Host: 127.0.0.1:8000
//HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//Upgrade: h2c
//User-Agent: Java-http-client/18.0.1.1
//
//some body text

final boolean equals (Object obj)

このHTTPリクエスト・インスタンスが指定されたオブジェクトと等しいかどうかをテストします。

final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).build();
final var request2 = HttpRequest.newBuilder(uri).build();

System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://example.com/ GET
System.out.println(request1.equals(request2)); // true
final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).GET().build();
final var request2 = HttpRequest.newBuilder(uri).DELETE().build();

System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://example.com/ DELETE
System.out.println(request1.equals(request2)); // false

abstract boolean expectContinue ()

このリクエスト「続行の予定」設定を返します。

final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
        .expectContinue(true)
        .build();

System.out.println(request); // https://example.com/ GET
System.out.println(request.expectContinue()); // true
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri).build();

System.out.println(request); // https://example.com/ GET
System.out.println(request.expectContinue()); // false

final int hashCode ()

このHTTPリクエスト・インスタンスのハッシュ・コードを計算します。

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

final var request1 = HttpRequest.newBuilder(uri).build();
System.out.println(request1.hashCode()); // 458519378

final var request2 = HttpRequest.newBuilder(uri).DELETE().build();
System.out.println(request2.hashCode()); // -1823680057
final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request.hashCode()); // 951755564

abstract HttpHeaders headers ()

(user-accessible)リクエスト・ヘッダーは、このリクエストが送信された(または)でした。

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

final var request = HttpRequest.newBuilder(uri)
        .POST(HttpRequest.BodyPublishers.ofString("xyz"))
        .header("Content-Type", "text/plain; charset=utf-8")
        .header("Content-Language", "en")
        .build();

System.out.println(request); // https://example.com/ POST

final var headers = request.headers();

// {Content-Language=[en], Content-Type=[text/plain; charset=utf-8]}
System.out.println(headers.map());

abstract String method ()

このリクエストのリクエスト・メソッドを返します。

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

final var request1 = HttpRequest.newBuilder(uri).build();

System.out.println(request1); // https://example.com/ GET
System.out.println(request1.method()); // GET

final var request2 = HttpRequest.newBuilder(uri)
        .POST(HttpRequest.BodyPublishers.ofString("xyz"))
        .build();

System.out.println(request2); // https://example.com/ POST
System.out.println(request2.method()); // POST

final var request3 = HttpRequest.newBuilder(uri).DELETE().build();

System.out.println(request3); // https://example.com/ DELETE
System.out.println(request3.method()); // DELETE

final var request4 = HttpRequest.newBuilder(uri).HEAD().build();

System.out.println(request4); // https://example.com/ HEAD
System.out.println(request4.method()); // HEAD

static HttpRequest.Builder newBuilder ()

HttpRequestビルダーを作成します。

newBuilder(URI uri) の使用例も合わせてご確認ください。

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

final var request = HttpRequest.newBuilder().uri(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

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

System.out.println(response); // (GET http://127.0.0.1:8000/) 200

// -- jwebserver --
//127.0.0.1 - - [24/Jul/2022:17:06:32 +0900] "GET / HTTP/1.1" 200 -
//Resource requested: R:\java-work
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> Upgrade: h2c
//> User-agent: Java-http-client/18.0.1.1
//> Content-length: 0
//>
//< Date: Sun, 24 Jul 2022 08:06:32 GMT
//< Last-modified: Sun, 24 Jul 2022 04:58:24 GMT
//< Content-type: text/html
//< Content-length: 6

static HttpRequest.Builder newBuilder (HttpRequest request, BiPredicate<String,String> filter)

既存のHttpRequestから初期状態がコピーされるBuilderを作成します。

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

final var request = HttpRequest.newBuilder(uri)
        .header("aaa", "xxx")
        .header("bbb", "yyy")
        .header("ccc", "zzz")
        .build();

System.out.println(request); // https://example.com/ GET
System.out.println(request.headers().map()); // {aaa=[xxx], bbb=[yyy], ccc=[zzz]}

final var ret1 = HttpRequest.newBuilder(request, (n, v) -> true).build();
System.out.println(ret1); // https://example.com/ GET
System.out.println(ret1.headers().map()); // {aaa=[xxx], bbb=[yyy], ccc=[zzz]}

final var ret2 = HttpRequest.newBuilder(request, (n, v) -> false).build();
System.out.println(ret2); // https://example.com/ GET
System.out.println(ret2.headers().map()); // {}

final var ret3 = HttpRequest.newBuilder(request, (name, value) -> !name.equals("bbb")).build();
System.out.println(ret3); // https://example.com/ GET
System.out.println(ret3.headers().map()); // {aaa=[xxx], ccc=[zzz]}

static HttpRequest.Builder newBuilder (URI uri)

指定されたURIのHttpRequestビルダーを作成します。

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

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

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

System.out.println(response); // (GET http://127.0.0.1:8000/) 200
System.out.println(response.body()); // abcd

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe -o verbose
//Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
//Serving R:\java-work and subdirectories on 127.0.0.1 port 8000
//URL http://127.0.0.1:8000/
//127.0.0.1 - - [24/Jul/2022:15:15:18 +0900] "GET / HTTP/1.1" 200 -
//Resource requested: R:\java-work
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> User-agent: Java-http-client/18.0.1.1
//> Upgrade: h2c
//> Content-length: 0
//>
//< Date: Sun, 24 Jul 2022 06:15:18 GMT
//< Last-modified: Sun, 24 Jul 2022 04:58:24 GMT
//< Content-type: text/html
//< Content-length: 6
//<

abstract Optional<Duration> timeout ()

このリクエスト・タイムアウト期間を含むOptionalを返します。

// タイムアウトを起こすために、jwebserver に対して意図的に HTTPS で接続します。
final var uri = URI.create("https://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri)
        .timeout(Duration.ofSeconds(15))
        .build();
System.out.println(request); // http://127.0.0.1:8000/ GET
System.out.println(request.timeout()); // Optional[PT15S]

final var client = HttpClient.newHttpClient();

final var startTime = System.nanoTime();

try {
    System.out.println("-- send request --");
    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (HttpConnectTimeoutException e) {
    System.out.println(e);

    final var endTime = System.nanoTime();
    System.out.println("timeout : " + (endTime - startTime) / 1000000000.0 + " sec.");
}

// 結果
// ↓
//-- send request --
//java.net.http.HttpConnectTimeoutException: HTTP connect timed out
//timeout : 15.0218707 sec.
final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request.timeout()); // Optional.empty

abstract URI uri ()

このリクエストURIを返します。

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

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.uri()); // https://example.com/

abstract Optional<HttpClient.Version> version ()

このHttpRequestにリクエストされるHTTPプロトコル・バージョンを含むOptionalを返します。

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

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET
System.out.println(request.version()); // Optional.empty

final var client = HttpClient.newHttpClient();
System.out.println(client.version()); // HTTP_2

final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response); // (GET http://127.0.0.1:8000/) 200

// -- jwebserver --
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> User-agent: Java-http-client/18.0.1.1
//> Upgrade: h2c
//> Content-length: 0
//>
//< Date: Sun, 24 Jul 2022 07:54:34 GMT
//< Last-modified: Sun, 24 Jul 2022 04:58:24 GMT
//< Content-type: text/html
//< Content-length: 6
final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri)
        .version(HttpClient.Version.HTTP_1_1)
        .build();
System.out.println(request); // http://127.0.0.1:8000/ GET
System.out.println(request.version()); // Optional[HTTP_1_1]

final var client = HttpClient.newHttpClient();
System.out.println(client.version()); // HTTP_2

final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response); // (GET http://127.0.0.1:8000/) 200

// -- jwebserver --
//> Host: 127.0.0.1:8000
//> User-agent: Java-http-client/18.0.1.1
//> Content-length: 0
//>
//< Date: Sun, 24 Jul 2022 07:55:28 GMT
//< Last-modified: Sun, 24 Jul 2022 04:58:24 GMT
//< Content-type: text/html
//< Content-length: 6

関連記事

ページの先頭へ