Handling response body types can be accomplished using HttpResponse.BodyHandler. The API comes with several implementations of this interface (BodyHandler) in the HttpResponse.BodyHandlers class, as follows:
- BodyHandlers.ofByteArray()
- BodyHandlers.ofFile()
- BodyHandlers.ofString()
- BodyHandlers.ofInputStream()
- BodyHandlers.ofLines()
Considering the following request, let's look at several solutions for handling the response body:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
We'll look at how to handle different types of response bodies in the following sections.