How would you implement connection-level HTTP/2 server push handling using HttpClient's PushPromiseHandler, and in what scenario would a server proactively push additional resources?
Short answer
HTTP/2 server push lets a server proactively send additional resources to a client alongside a requested resource, anticipating the client will need them shortly (like pushing a CSS/JS file alongside the HTML page that references them, avoiding the client needing to make a…
Advertisement
AModel answer
HTTP/2 server push lets a server proactively send additional resources to a client alongside a requested resource, anticipating the client will need them shortly (like pushing a CSS/JS file alongside the HTML page that references them, avoiding the client needing to make a separate subsequent request and round-trip for each one) -- HttpClient supports receiving these pushed resources via an optional PushPromiseHandler supplied to the send()/sendAsync() call, which receives a callback for each pushed resource with its own associated HttpRequest/HttpResponse pair, letting client code process pushed resources alongside the originally-requested one.
PushPromiseHandler<String> pushHandler = (initialRequest, pushPromiseRequest, acceptor) -> {
CompletableFuture<HttpResponse<String>> pushedResponse =
acceptor.apply(HttpResponse.BodyHandlers.ofString());
pushedResponse.thenAccept(resp ->
System.out.println("Received pushed resource: " + pushPromiseRequest.uri() + " -> " + resp.statusCode()));
};
client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushHandler);Real-world example
A web application server using HTTP/2 push proactively sends a page's associated CSS and JavaScript bundle alongside the initially requested HTML document, and a compatible HttpClient-based test tool verifies this push behavior works correctly by implementing a PushPromiseHandler that logs each received pushed resource.
Likely follow-ups
- Why has HTTP/2 server push become less commonly used in practice despite its theoretical performance benefits, particularly for browser-based clients?
- What happens if a server sends a pushed resource but the client's request doesn't include a PushPromiseHandler at all?
Related topics