Handle HTTP chunked responses - Java edition
The Domino REST API delivers collections using chunked transfer encoding. This has the advantage, that you can process results as they arrive. It produces the challenge that the usual client side code is designed to first wait for completion of the request. I wrote about the JavaScript solution a while ago, this is the Java edition.
Client choices
In JavaScript land the choice of client is simple: the Fetch API. In Java we have some choices:
- Since Java 11 there's a HttpClient in the JDK
- A very popular library is provided by the Apache HTTP components
- The SPRING framework, undisputed king of Java web frameworks, offers its own sset of clients
- The vert.x framework, which we used to build DRAPI, features its own client
There are probably more around. This article uses the JDK HttpClient. I'll skip the parts with Authentication and TLS handling, check the full example for details.
How it works
First we create an java.net.http.HttpClient. It takes care of the http version and the TLS context.
HttpClient getClient(SSLContext sslContext) {
return HttpClient.newBuilder()
.sslContext(sslContext)
.build();
}
Then we build and execute the request. The magic is the BodySubscriber (more on that below).
Integer runGetRequest(HttpClient client, String url, String authHeader, BodySubscriber subscriber) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", authHeader)
.GET()
.build();
CompletableFuture<Integer> response =
client.sendAsync(request, responseInfo -> subscriber)
.whenComplete((r, t) -> System.out.println("Response: " + r.statusCode()))
.thenApply(HttpResponse::body);
return response.get();
}
Read more
Posted by Stephan H Wissel on 09 October 2024 | Comments (0) | categories: Java WebDevelopment