Sub topic 16
HTTP/1.1 and HTTP/2
Assume you understand Java 11 syntax, HTTP requests and responses, and checked exceptions. This chapter focuses on choosing a protocol version with HttpClient and checking which version the server actually used.
The two HTTP versions
HTTP/1.1 sends requests over a connection in a mostly sequential way. A client can open several connections to improve concurrency, but each connection has limits. HTTP/1.1 also repeats many headers in each request.
HTTP/2 keeps the request and response model but changes how messages travel. One connection can carry many independent streams at the same time. It also compresses headers and splits data into frames. These changes can reduce connection overhead and prevent one slow response from blocking other requests on the same connection.
| Feature | HTTP/1.1 | HTTP/2 |
|---|---|---|
| Multiple requests per connection | Limited by connection behavior | Multiplexed streams |
| Header compression | No standard header compression | Yes |
| Message format | Text-oriented protocol messages | Binary frames |
| Java selection | `HTTP_1_1` | `HTTP_2` |
Selecting a preferred version
Use HttpClient.Builder.version when building the client. This setting is a preference, not a guarantee. If you prefer HTTP/2 but the server or a proxy cannot use it, the client can fall back to HTTP/1.1.
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 HttpVersionDemo {
public static void main(String[] args)
throws java.io.IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Used protocol: " + response.version());
System.out.println("Status: " + response.statusCode());
}
}response.version() reports the protocol used for that response. It may return HTTP_2 even though the client was configured with a preference for HTTP/2, or HTTP_1_1 after fallback.
Common errors and trade-offs
- Do not assume that
.version(HTTP_2)forces HTTP/2. Always inspectresponse.version()when the protocol matters. - HTTPS commonly negotiates HTTP/2 through TLS application-layer protocol negotiation, or ALPN. TLS settings, proxies, and server configuration can affect the result.
- HTTP/2 multiplexing improves concurrency, but it does not make a slow server faster. Timeouts and status-code checks still apply.
- Reuse one
HttpClientfor related requests. The client can reuse connections and manage multiple HTTP/2 streams.
Exercise
How can you verify whether a request actually used HTTP/2?
Show answer
Call response.version() and compare the result with HttpClient.Version.HTTP_2.