広告

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

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


概要

HTTPリクエスト。

クラス構成

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

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

などの属性を持ちます。

補足

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

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

try (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 - - [31/Mar/2024:18:21:21 +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/21.0.1
//> Upgrade: h2c
//>
//< Date: Sun, 31 Mar 2024 09:21:21 GMT
//< Last-modified: Sun, 31 Mar 2024 07:01:20 GMT
//< Content-type: text/html
//< Content-length: 4
//<

コンストラクタ

HttpRequest ()

HttpRequestを作成します。

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

メソッド

abstract Optional<HttpRequest.BodyPublisher> bodyPublisher ()

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

このコード例では node.js をテストサーバとして使います。

// 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 bodyPublisher = HttpRequest.BodyPublishers.ofString("post text");

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

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

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

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 uri1 = URI.create("https://example.com/");
final var uri2 = URI.create("https://www.example.com/");

final var request1 = HttpRequest.newBuilder(uri1).build();
final var request2 = HttpRequest.newBuilder(uri2).build();

System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://www.example.com/ GET
System.out.println(request1.equals(request2)); // false
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ビルダーを作成します。

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

try (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
}

// -- PowerShell --
//PS R:\java-work> jwebserver.exe
// ...
//127.0.0.1 - - [31/Mar/2024:18:44:07 +0900] "GET / HTTP/1.1" 200

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, (name, value) -> 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, (name, value) -> 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

try (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
// ...
//127.0.0.1 - - [31/Mar/2024:18:45:10 +0900] "GET / HTTP/1.1" 200 -

abstract Optional<Duration> timeout ()

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

// タイムアウトを起こすために、example.com に対して意図的に 8000 ポートを使います。
final var uri = URI.create("https://example.com:8000/");

final var request = HttpRequest.newBuilder(uri)
        .timeout(Duration.ofSeconds(5))
        .build();
System.out.println(request); // https://example.com:8000/ GET
System.out.println(request.timeout()); // Optional[PT5S]

final var startTime = System.nanoTime();

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

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

// 結果
// ↓
//-- send request --
//java.net.http.HttpConnectTimeoutException: HTTP connect timed out
//timeout : 5.0179335 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("https://example.com/");

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

try (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 https://example.com/) 200
    System.out.println(response.version()); // HTTP_2
}
final var uri = URI.create("https://example.com/");

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

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET https://example.com/) 200
    System.out.println(response.version()); // HTTP_1_1
}

関連記事

ページの先頭へ