Sub topic 2
The three core types: HttpClient, HttpRequest, HttpResponse
This chapter assumes you know Java 11 syntax, what HTTP methods, status codes and headers are, and how checked exceptions work. It introduces the three types that every java.net.http call uses, and what each one owns. Later chapters cover each in detail.
Three types, three jobs
The java.net.http package splits an HTTP call into three objects.
| Type | Represents | Lifetime | Created with |
|---|---|---|---|
| `HttpClient` | The configuration and connection machinery | Long-lived, shared | `HttpClient.newBuilder()` or `HttpClient.newHttpClient()` |
| `HttpRequest` | One request: URI, method, headers, optional body | One per call | `HttpRequest.newBuilder(uri)` |
| `HttpResponse<T>` | One response: status, headers, body of type `T` | One per call | Returned by `send` or `sendAsync` |
All three are immutable once built. You never change a request or response. You build a new one.
HttpClient: the long-lived part
An HttpClient holds everything that outlives a single call:
- Protocol preference (HTTP/1.1 or HTTP/2).
- Redirect policy.
- Connect timeout.
- Proxy, cookie handler, authenticator and TLS settings.
- A pool of connections that later requests can reuse.
- The executor that runs asynchronous work.
Because it owns the connection pool, you should create one client and reuse it. A new client per request throws away connection reuse and wastes threads. A client is thread-safe, so any number of threads can share it.
The quickest way to get one is HttpClient.newHttpClient(). It uses defaults: HTTP/2 preferred with fallback to HTTP/1.1, redirects never followed, and no connect timeout. For real work, use the builder:
import java.net.http.HttpClient;
import java.time.Duration;
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build();HttpRequest: the per-call part
An HttpRequest describes exactly one request. It has a URI, a method, headers, an optional body and an optional timeout. The builder requires a URI. If you never choose a method, you get GET.
import java.net.URI;
import java.net.http.HttpRequest;
import java.time.Duration;
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.header("Accept", "text/html")
.GET()
.build();Two things to keep in mind:
- The
timeouton a request limits how long you wait for the response. It is separate from the client's connect timeout. - A request does not know which client will send it. The same request object can be sent more than once, by one client or several.
A request exposes getters such as uri(), method(), headers() and timeout(). Optional parts return Optional, for example timeout() and bodyPublisher().
HttpResponse<T>: the typed result
HttpResponse<T> is generic because the body type depends on how you asked for it. You choose the type with a BodyHandler<T> when you send. The table shows common choices.
| BodyHandler | Resulting type |
|---|---|
| `BodyHandlers.ofString()` | `HttpResponse<String>` |
| `BodyHandlers.ofByteArray()` | `HttpResponse<byte[]>` |
| `BodyHandlers.ofFile(path)` | `HttpResponse<Path>` |
| `BodyHandlers.ofInputStream()` | `HttpResponse<InputStream>` |
| `BodyHandlers.discarding()` | `HttpResponse<Void>` |
The response gives you these accessors:
statusCode()returns the numeric status as anint.headers()returns anHttpHeadersobject. Header names are case-insensitive.body()returns the body as typeT.request()anduri()return the request that produced the response and the final URI.version()returns the protocol actually used.previousResponse()returns anOptionalholding the earlier response when a redirect was followed.
Putting the three together
This program builds a client, builds a request, sends it, and inspects the response. It is complete and runnable.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class ThreeTypes {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.header("Accept", "text/html")
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Version: " + response.version());
System.out.println("Type: "
+ response.headers().firstValue("Content-Type").orElse("unknown"));
System.out.println("Length: " + response.body().length());
}
}firstValue returns an Optional<String>, because a header may be missing. Use allValues when a header can repeat, as Set-Cookie does.
Sync and async share the same shapes
The client has two sending methods:
send(request, handler)blocks the calling thread and returnsHttpResponse<T>. It throwsIOExceptionandInterruptedException.sendAsync(request, handler)returns immediately with aCompletableFuture<HttpResponse<T>>.
Both take the same request and the same handler. Only the way you wait for the result changes. Failures from sendAsync surface when the future completes, not at the call site.
Common mistakes
- Creating a client per call. This wastes connections and threads. Keep one client in a field or a singleton.
- Expecting an exception for a 404 or 500. The client treats any response it can read as a success at the transport level. Check
statusCode()yourself. - Forgetting the redirect policy. A
3xxthen appears as the final response, with an empty or small body. - Mixing up the two timeouts. The client's
connectTimeoutapplies only to establishing the connection. The request'stimeoutcovers waiting for the response. - Assuming the request carries the client's settings. Redirects, proxy and version preferences belong to the client. Headers, body and request timeout belong to the request.
Exercise
You wrote a helper that builds a new HttpClient, sends one GET, and returns the body as a String. It is called hundreds of times per minute. Which of the three types should be created once, which per call, and what type does the body have if you pass BodyHandlers.ofByteArray()?
Show answer
Create the HttpClient once and share it, because it owns the connection pool and is thread-safe. Create an HttpRequest per call (it is cheap and immutable). The response is an HttpResponse<byte[]>, so body() returns a byte[].
Exercise
A request to a URL returns statusCode() 301 with no exception, and the body is empty. Name the likely cause and the fix.
Show answer
The client uses the default redirect policy NEVER, so the 301 is returned as-is. Build the client with followRedirects(HttpClient.Redirect.NORMAL) so it follows the Location header.