JackPGreen
JackPGreen

Reputation: 1139

java.net.http.HttpClient - Why would HttpResponse.body be null?

My application connects to an internet resource using java.net.http.HttpClient.

I would expect it to either connect and work, or to throw an exception - and this is how it always seems to work.

However, looking through logs I can see for another user, it did neither and instead returned a HttpResponse with a null body. For reference, this was running on Amazon Corretto 11.0.13.

I'm not able to reproduce this, and from looking at the documentation and the code it's not clear how or why this can happen.

An example of what the application is doing:

try {
    final HttpResponse<InputStream> response = HttpClient.newHttpClient().send(HttpRequest.newBuilder(new URI(
        "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation")).GET()
        .build(), BodyHandlers.ofInputStream());

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
        reader.lines().forEach(System.out::println);
    }
} catch (IOException | InterruptedException | URISyntaxException e) {
    e.printStackTrace();
}

And the following error was logged:

java.lang.NullPointerException
    at java.base/java.io.Reader.<init>(Reader.java:167)
    at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:109)

The error in the InputStreamReader constructor suggests response.body() returns null.

Obviously I could just catch the NullPointerException, but there's no context as to what problem occurred, which causes a problem when trying to resolve the connectivity issue.

Upvotes: 0

Views: 2347

Answers (1)

pepevalbe
pepevalbe

Reputation: 1380

There are other scenarios where connection is ok but you can't get what you expect from the server. You should check the http response status codes and act accordingly.

As you see response.body() can be null so you should check agains that.

Upvotes: 1

Related Questions