Sub topic 4
Building requests: URI, method, headers
This chapter covers how to construct an HttpRequest. It assumes you know Java 11 syntax, HTTP methods and headers, and how HttpClient fits in from the earlier chapters. Sending the request and reading the response come in later chapters. The examples here only build requests and inspect them, so they run without a network.
The builder produces an immutable request
An HttpRequest is created through a builder. The builder is mutable, and every call on it returns the same builder so you can chain calls. build() produces an immutable request. You can send that request many times, from many threads, and it never changes.
A builder needs at least a URI before build() succeeds. If you forget it, build() throws IllegalStateException. The method defaults to GET.
The URI
You can pass the URI to newBuilder(URI) or call .uri(URI) later. Either way the URI must be absolute, with a scheme of http or https and a host. Anything else throws IllegalArgumentException, either from uri() or from build().
URI.create(String) also throws IllegalArgumentException when the string is not a valid URI. A space or a non-ASCII character in a query string is the usual cause. The HttpClient API does not build query strings for you, so you must encode the values yourself:
String q = URLEncoder.encode("café & tea", StandardCharsets.UTF_8);
URI uri = URI.create("https://api.example.com/search?q=" + q + "&limit=10");Encode each value separately, before you join the pieces with & and =. If you encode the whole query string, the separators are encoded too and the server reads one long value.
URLEncoder is built for HTML form encoding, so it writes a space as +. That is correct in a query string. It is wrong in a URL path, where a space should be %20. For path segments, the multi-argument URI constructors encode illegal characters for you.
Choosing the method
The builder has a shortcut for each common method, and one general method for the rest.
| Call | HTTP method | Body |
|---|---|---|
| `GET()` | GET | none |
| `DELETE()` | DELETE | none |
| `POST(publisher)` | POST | required |
| `PUT(publisher)` | PUT | required |
| `method("PATCH", publisher)` | any name you give | required (use `noBody()` for none) |
PATCH has no shortcut, so use method. HEAD() was only added in Java 18. On Java 11 to 17, write method("HEAD", HttpRequest.BodyPublishers.noBody()). The body publishers are covered in a later chapter. For now, ofString is enough.
Calling a method shortcut more than once is not an error. The last call wins.
Headers
Three builder methods set headers:
header(name, value)adds a value. Calling it twice with the same name sends two values for that header.setHeader(name, value)removes any existing values for that name and then sets one.headers(String... pairs)adds several name and value pairs at once. It requires an even number of arguments.
Header names are case-insensitive. The request's HttpHeaders object reflects this: allValues("x-trace") finds a header you set as X-Trace.
Here is a complete program that builds requests and prints what the builder produced:
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
public class RequestDemo {
public static void main(String[] args) {
String q = URLEncoder.encode("café & tea", StandardCharsets.UTF_8);
URI uri = URI.create("https://api.example.com/search?q=" + q + "&limit=10");
HttpRequest get = HttpRequest.newBuilder(uri)
.GET()
.header("Accept", "application/json")
.header("X-Trace", "a")
.header("X-Trace", "b")
.timeout(Duration.ofSeconds(10))
.build();
System.out.println(get);
System.out.println(get.method());
System.out.println(get.headers().allValues("x-trace"));
HttpRequest replaced = HttpRequest.newBuilder(uri)
.header("Accept", "text/plain")
.setHeader("Accept", "application/json")
.build();
System.out.println(replaced.headers().allValues("Accept"));
HttpRequest patch = HttpRequest.newBuilder(URI.create("https://api.example.com/items/7"))
.method("PATCH", HttpRequest.BodyPublishers.ofString("{\"name\":\"gadget\"}"))
.header("Content-Type", "application/json")
.build();
System.out.println(patch.method());
}
}The first line prints the URI followed by the method. x-trace finds both values, [a, b]. The second request prints [application/json] because setHeader discarded text/plain.
Headers you cannot set
The client manages a few headers itself. Trying to set one with header or setHeader throws IllegalArgumentException immediately, before build():
connectioncontent-lengthexpecthostupgrade
try {
HttpRequest.newBuilder(URI.create("https://example.com/"))
.header("Host", "other.example.com");
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}Content-Length is derived from the body publisher, and Host comes from the URI. For Expect: 100-continue, use expectContinue(true) on the builder instead. A JDK system property, jdk.httpclient.allowRestrictedHeaders, can relax the restriction in Java 12 and later. Leave it alone unless you are testing against a server that needs unusual headers.
Header names and values are also validated against HTTP syntax. A value containing a newline is rejected. This prevents header injection when part of a value comes from user input.
Headers the client adds for you
If you do not set User-Agent, the client sends Java-http-client/ followed by the JDK version. Some APIs reject or throttle unknown agents. If you hit this, set your own with header("User-Agent", "my-app/1.0").
For a request with a body, you must set Content-Type yourself. The publisher knows the bytes but not what they mean.
Per-request options
Two more builder calls affect how a single request is sent:
timeout(Duration)limits how long the client waits for the response. A later chapter covers timeouts in detail. The duration must be positive, otherwiseIllegalArgumentException.version(HttpClient.Version)asks for HTTP/1.1 or HTTP/2 for this request. It overrides the client's default version.
Common mistakes
- Putting a raw space or a non-ASCII character in a URI string. This fails in
URI.create, not in the HTTP client. - Using
headerwhen you meantsetHeader. You then send duplicateAcceptorAuthorizationvalues, and servers disagree on which one wins. - Forgetting
Content-Typeon a POST. The server then often replies415 Unsupported Media Typeor reads the body as the wrong format. - Treating the builder as thread-safe. Share built requests, not builders.
Exercise
You call .header("Accept", "text/plain") and then .header("Accept", "application/json") on one builder. What does the request send, and which call would you use to send only application/json?
Show answer
It sends both values for Accept, because header adds rather than replaces. Using setHeader("Accept", "application/json") for the second call removes the earlier value and sends only application/json.
Exercise
On Java 11, how do you build a HEAD request, and why does .header("Content-Length", "0") fail?
Show answer
Use method("HEAD", HttpRequest.BodyPublishers.noBody()), because the HEAD() shortcut only exists from Java 18. Content-Length is a restricted header that the client derives from the body publisher, so setting it throws IllegalArgumentException.