Build and inspect an HTTP request in Java

Construct a GET request and inspect its metadata entirely in memory. A timeout belongs to the request, while the host comes from its URI.

A simple example

Build a GET request in memory

  1. Start with A URI with the path /a
  2. Do this Build a GET request in memory
  3. Result Method GET
Building a request object lets you inspect it without contacting the host.

Apply it to a real problem

  1. Start with A report request to example.org
  2. Do this Inspect method, host and timeout
  3. Result GET, example.org, 3 seconds
The client can verify its request configuration before sending it.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.net.URI;
import java.net.http.HttpRequest;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        var request = HttpRequest.newBuilder(URI.create("https://example.org/reports"))
                .timeout(Duration.ofSeconds(3)).GET().build();
        System.out.println(request.method() + " " + request.uri().getHost());
        System.out.println(request.timeout().orElseThrow().toSeconds() + " seconds");
    }
}
Output
GET example.org
3 seconds

Official Java documentation