CodexBloom - Programming Q&A Platform

Java 11: Unexpected NPE when using CompletableFuture and HttpClient with async requests

👀 Views: 52 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
java httpclient completablefuture exception Java

I'm following best practices but I've been banging my head against this for hours. I'm working on a project and hit a roadblock. I tried several approaches but none seem to work. I'm encountering a `NullPointerException` when using `CompletableFuture` with the new `HttpClient` introduced in Java 11. My intention is to make multiple asynchronous HTTP requests and collect their results, but I'm running into issues when I try to process the responses. Here's a simplified version of my code: ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.concurrent.CompletableFuture; public class AsyncHttpExample { private static final HttpClient client = HttpClient.newHttpClient(); public static void main(String[] args) { CompletableFuture<HttpResponse<String>> future1 = fetchData("https://api.example.com/data1"); CompletableFuture<HttpResponse<String>> future2 = fetchData("https://api.example.com/data2"); CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2); combinedFuture.thenRun(() -> { try { String response1 = future1.get().body(); // This line throws NPE String response2 = future2.get().body(); System.out.println(response1); System.out.println(response2); } catch (Exception e) { e.printStackTrace(); } }); } private static CompletableFuture<HttpResponse<String>> fetchData(String uri) { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(uri)) .build(); return client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); } } ``` I've verified that both URIs are valid and reachable, and I can confirm that the requests return a status code of 200 when made synchronously. However, the `CompletableFuture` results seem to cause an NPE when I attempt to access the response bodies. I've also checked that `future1` and `future2` are not null at the time I call `get()`. Any ideas on what could be going wrong or how to properly handle these asynchronous calls to avoid the NPE? I'm working on a application that needs to handle this. Thanks in advance! I'd really appreciate any guidance on this. I'm open to any suggestions.