広告

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

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


概要

HTTPレスポンス。

クラス構成

HttpResponse は HTTP通信の要求(HttpRequest) の結果を表すクラスです。

  • ステータスコード(成功:200、ページが見つからない:404、などなど)
  • 本文(body)

といった属性を持ちます。

補足

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 - - [04/Apr/2024:15:49:13 +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/21.0.1
//>
//< Date: Thu, 04 Apr 2024 06:49:13 GMT
//< Last-modified: Thu, 4 Apr 2024 06:46:40 GMT
//< Content-type: text/html
//< Content-length: 4
//<

メソッド

T body ()

本文を返します。

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 handler = HttpResponse.BodyHandlers.ofString();
    final var response = client.send(request, handler);

    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 - - [04/Apr/2024:15:51:15 +0900] "GET / HTTP/1.1" 200 -
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 handler = HttpResponse.BodyHandlers.ofByteArray();
    final var response = client.send(request, handler);

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
    System.out.println(Arrays.toString(response.body())); // [97, 98, 99, 100]
}

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:51:15 +0900] "GET / HTTP/1.1" 200 -

HttpHeaders headers ()

受信したレスポンス・ヘッダーを返します。

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("-- headers --");
    for (final var header : response.headers().map().entrySet()) {
        System.out.println(header.getKey() + " : " + header.getValue());
    }
}

// 結果
// ↓
//-- headers --
//content-length : [4]
//content-type : [text/html]
//date : [Thu, 04 Apr 2024 06:52:27 GMT]
//last-modified : [Thu, 4 Apr 2024 06:46:40 GMT]

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:52:27 +0900] "GET / HTTP/1.1" 200 -

Optional<HttpResponse<T>> previousResponse ()

以前の中間レスポンスを受信した場合はそれを含むOptionalを返します。

リダイレクト用のテストサーバとして Apache HTTP Server を使っています。
http://192.168.1.9/redirect-test/src.html にアクセスすると https://example.com/ へリダイレクトします。

xxxx@xxxx:/var/www/html/redirect-test$ cat .htaccess
RewriteEngine on
RewriteRule ^src.html$ https://example.com/ [L,R=301]
final var uri = URI.create("http://192.168.1.9/redirect-test/src.html");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://192.168.1.9/redirect-test/src.html GET

try (final var client = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build()) {

    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET https://example.com/) 200

    // Optional[(GET http://192.168.1.9/redirect-test/src.html) 301]
    System.out.println(response.previousResponse());
}

HttpRequest request ()

このレスポンスに対応する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

    final var ret = response.request();
    System.out.println(ret); // http://127.0.0.1:8000/ GET
    System.out.println(ret.equals(request)); // true
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:57:47 +0900] "GET / HTTP/1.1" 200 -

Optional<SSLSession> sslSession ()

このレスポンスに有効なSSLSessionを含むOptionalを返します。

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

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

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

    System.out.println(response); // (GET https://example.com/) 200

    response.sslSession().ifPresent(ssl -> {
        System.out.println(ssl.getPeerHost()); // example.com
        System.out.println(ssl.getProtocol()); // TLSv1.3
        System.out.println(ssl.getCipherSuite()); // TLS_AES_256_GCM_SHA384
    });
}

int statusCode ()

このレスポンスのステータス・コードを返します。

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.statusCode()); // 200
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:59:43 +0900] "GET / HTTP/1.1" 200 -
final var uri = URI.create("http://127.0.0.1:8000/");

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

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

    System.out.println(response); // (DELETE http://127.0.0.1:8000/) 405
    System.out.println(response.statusCode()); // 405
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:59:43 +0900] "DELETE / HTTP/1.1" 405 -

URI uri ()

レスポンスの受信元のURIを返します。

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.uri()); // http://127.0.0.1:8000/
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:16:00:32 +0900] "GET / HTTP/1.1" 200 -

HttpClient.Version version ()

このレスポンスに使用されたHTTPプロトコル・バージョンを返します。

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()) {
    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
    System.out.println(response.version()); // HTTP_1_1
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:16:01:57 +0900] "GET / HTTP/1.1" 200 -
final var uri = URI.create("https://example.com/");

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

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
}

関連記事

ページの先頭へ