Sub topic 17
HTTP/1.1 and HTTP/2
This chapter assumes you can already build an HttpClient, send a request with send, and read statusCode() and body() from the response. It covers how the client chooses an HTTP version, how to find out which version was used, and when forcing a version is worth doing.
What the version setting controls
HttpClient.Version is an enum with two values: HTTP_1_1 and HTTP_2. The version is a preference, not a guarantee. Your code looks the same under both versions, because the same HttpRequest, BodyHandler and HttpResponse types apply.
The two versions differ in how they use the network:
| Aspect | HTTP/1.1 | HTTP/2 |
|---|---|---|
| Wire format | Text lines | Binary frames |
| Requests per connection | One at a time | Many at once (multiplexing) |
| Connections to one host | Several, pooled | Usually one |
| Header compression | None | HPACK |
| Header names | Any case | Lower case on the wire |
Multiplexing is the main benefit. With HTTP/1.1, ten parallel requests to one host need up to ten connections, or they queue behind each other. With HTTP/2, they share one connection as interleaved streams.
The default is HTTP/2 with fallback
A client built without a version setting prefers HTTP/2. This is the same as calling version(HttpClient.Version.HTTP_2) yourself. Asking for HTTP/2 does not make a request fail when the server only speaks HTTP/1.1. The client falls back to HTTP/1.1 instead.
The negotiation depends on the URI scheme:
https: The client offersh2andhttp/1.1during the TLS handshake, using an extension called ALPN. The server picks one.http: There is no TLS handshake, so the client sends anUpgrade: h2cheader on an HTTP/1.1 request. A server that supports cleartext HTTP/2 switches protocols. Most servers ignore the header, and the exchange stays on HTTP/1.1.
Checking which version was used
HttpResponse.version() reports the protocol that carried the exchange. Always read it from the response. The version you requested tells you nothing about what happened.
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 VersionCheck {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
HttpResponse<Void> response =
client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println("Requested: " + client.version());
System.out.println("Used: " + response.version());
System.out.println("Status: " + response.statusCode());
}
}BodyHandlers.discarding() drops the body, which is enough when you only want the status and protocol. Against a server with HTTP/2 enabled, this prints HTTP_2 for "Used". Against an HTTP/1.1-only server, it prints HTTP_1_1 for "Used" and the request still succeeds.
Forcing HTTP/1.1
Set the version on the client to use HTTP/1.1 for everything. Set it on a single request to override the client's choice for that call only. The request builder has its own version method.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ForceVersion {
public static void main(String[] args) throws Exception {
// Client-wide: every request prefers HTTP/1.1.
HttpClient http1Client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
// Per request: this call prefers HTTP/1.1 even on an HTTP/2 client.
HttpClient defaultClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
System.out.println(http1Client.send(request, HttpResponse.BodyHandlers.discarding()).version());
System.out.println(defaultClient.send(request, HttpResponse.BodyHandlers.discarding()).version());
}
}Both lines print HTTP_1_1. The per-request setting wins over the client's setting.
When to change the default
Leave the default in place unless you have a specific reason. Reasons to force HTTP/1.1:
- A proxy, load balancer or legacy server mishandles HTTP/2 and you see resets or hangs.
- You are comparing behavior between the two versions while debugging.
- A server rejects the
Upgrade: h2cheader on plainhttpURIs. This is rare but happens with strict servers.
There is no reason to force HTTP/2 for correctness. Because fallback is automatic, requesting HTTP/2 is already the best-effort choice.
Gotchas
- Concurrency looks different. With HTTP/2, parallel
sendAsynccalls to one host share a connection. A server may cap concurrent streams per connection, and the extra requests wait for a free stream. This is normal and not a bug in your code. - Header case. HTTP/2 lower-cases header names.
response.headers()looks names up case-insensitively, sofirstValue("Content-Type")works under both versions. Code that compares raw header names withequalsbreaks. - Restricted headers. The client refuses to let you set some headers, including
Connection,Content-Length,Host,UpgradeandExpect. It manages them itself. Trying to set one throwsIllegalArgumentExceptionwhen you build the request. This matters here because connection-level headers mean different things in the two versions. - Reuse the client. Connection pooling and HTTP/2 multiplexing both live inside one
HttpClientinstance. A new client per request discards the pooled connection and repeats the TCP and TLS handshakes. - Cleartext HTTP/2 is uncommon. Servers rarely accept
h2c. If a local test server overhttpalways reportsHTTP_1_1, that is expected.
Summary of decisions
- Build one shared client and keep the default version.
- Read
response.version()when you need to know what actually ran. - Use
.version(HTTP_1_1)on the client or on a request only to work around a misbehaving server or to compare behavior.
Exercise
You build a client with .version(HttpClient.Version.HTTP_2) and send a request to an http:// (not https://) URL. response.version() returns HTTP_1_1 and the status is 200. Did something go wrong, and why did this happen?
Show answer
Nothing went wrong. HTTP/2 is only a preference. Over http the client sends an Upgrade: h2c header on an HTTP/1.1 request. Most servers ignore it, so the exchange stays on HTTP/1.1 and the request succeeds. Over https, the client would instead offer h2 through TLS ALPN, and the server would usually accept it.