Sub topic 3
Building requests: URI, method, headers
Assume you know basic HTTP methods, status codes, headers, Java 11 syntax, and checked exceptions. This chapter focuses on creating HttpRequest objects. Sending and interpreting those requests comes next.
A request is an immutable description
An HttpRequest describes one HTTP operation:
- A
URIidentifies the target resource. - An HTTP method says what operation to perform, such as
GETorPOST. - Headers carry metadata, such as the accepted response format.
- An optional body carries data sent to the server.
- A request timeout limits how long this request may wait.
The request does not send itself. You pass it to HttpClient.send or sendAsync.
URI, method, and headers
Use URI.create for a known, valid URI. It throws IllegalArgumentException when the text is not a valid URI, so validate or handle external input before building a request.
HttpRequest.newBuilder returns a builder. The builder collects settings, and build() creates the immutable request.
import java.net.URI;
import java.net.http.HttpRequest;
public class BuildRequests {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/items?limit=10"))
.timeout(java.time.Duration.ofSeconds(10))
.header("Accept", "application/json")
.header("User-Agent", "InventoryClient/1.0")
.GET()
.build();
System.out.println(request.method());
System.out.println(request.uri());
System.out.println(request.headers().firstValue("Accept").orElse("missing"));
}
}The method convenience functions include GET(), POST(...), PUT(...), and DELETE(). You can also use method("PATCH", publisher) for methods without a dedicated convenience function.
A header is a name-value pair. header adds one value. setHeader replaces existing values with the same name. Header names are case-insensitive, but use conventional spelling for readability.
Adding a request body
A BodyPublisher supplies bytes for the request body. BodyPublishers.ofString is suitable for small text or JSON payloads. Set Content-Type so the server knows how to interpret those bytes.
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.example.com/items"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"name\":\"widget\",\"quantity\":3}"))
.build();GET() normally has no body. Do not put authentication secrets in a URI query string because URIs often appear in logs and monitoring data.
Exercise
Which header should you set when a POST body contains JSON, and what does it describe?
Show answer
Set Content-Type to application/json. It describes the format of the bytes sent in the request body.