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
- Start with A URI with the path /a
- Do this Build a GET request in memory
- Result Method GET
Apply it to a real problem
- Start with A report request to example.org
- Do this Inspect method, host and timeout
- Result GET, example.org, 3 seconds
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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");
}
}
GET example.org 3 seconds