{{announcement.body}}
{{announcement.title}}

JDK 11 HTTP Client API - Handling Request/Response Body Types

DZone 's Guide to

JDK 11 HTTP Client API - Handling Request/Response Body Types

In this article, we discuss how to deal with requests and response body types in an HTTP client API in Java.

· Integration Zone ·
Free Resource

This article is a supersonic guide to dealing with request and response body types in an HTTP Client API. Let's start with the request body types.

Handling Request Body Types

Setting a request body can be accomplished using  HttpRequest.Builder.POST()  and PUT()  or by using  method()(for example, method("PATCH", HttpRequest.BodyPublisher)). The POST()  and  PUT()  take an argument of the  HttpRequest.BodyPublisher  type. 

The API comes with several implementations of this interface ( BodyPublisher ) in the HttpRequest.BodyPublishers  class, as follows:

  •  BodyPublishers.ofString() 
  •  BodyPublishers.ofFile() 
  •  BodyPublishers.ofByteArray() 
  •  BodyPublishers.ofInputStream() 

We'll take a look at these implementations in the following sections.

Creating a Body From a String

Creating a body from a string can be accomplished using  BodyPublishers.ofString() , as shown in the following snippet of code:

Java
 




x


 
1
HttpRequest requestBody = HttpRequest.newBuilder()
2
  .header("Content-Type", "application/json")
3
  .POST(HttpRequest.BodyPublishers.ofString(
4
    "{\"name\": \"morpheus\",\"job\": \"leader\"}"))
5
  .uri(URI.create("https://reqres.in/api/users"))
6
  .build();



For specifying a charset call, use ofString(String s, Charset charset).

Creating a body from InputStream

Creating a body from InputStream can be accomplished using BodyPublishers.ofInputStream(), as shown in the following snippet of code. (Here, we rely on ByteArrayInputStream, but, of course, any other InputStream is suitable):

Java
 




xxxxxxxxxx
1
16


 
1
HttpRequest requestBodyOfInputStream = HttpRequest.newBuilder()
2
.header("Content-Type", "application/json")
3
  .POST(HttpRequest.BodyPublishers.ofInputStream(()
4
      -> inputStream("user.json")))
5
  .uri(URI.create("https://reqres.in/api/users"))
6
  .build();
7
    
8
private static ByteArrayInputStream inputStream(String fileName) {
9
   
10
  try (ByteArrayInputStream inputStream = new ByteArrayInputStream(
11
    Files.readAllBytes(Path.of(fileName)))) {
12
    return inputStream;
13
  } catch (IOException ex) {
14
    throw new RuntimeException("File could not be read", ex);
15
  }
16
}



In order to take advantage of lazy creation, InputStream has to be passed as Supplier.

Creating a Body From a Byte Array

Creating a body from a byte array can be accomplished using  BodyPublishers.ofByteArray(), as shown in the following snippet of code:

Java


We can also send only a part of the byte array using ofByteArray(byte[] buf, int offset, int length). Moreover, we can provide data from an Iterable of byte arrays using ofByteArrays(Iterable<byte[]> iter).

Creating a Body From a File

Creating a body from a file can be accomplished using  BodyPublishers.ofFile(), as shown in the following snippet of code:

Java


All the above examples can be found on GitHub. Next, let's handle response body types.

Handling Response Body Types

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:

Java
 




xxxxxxxxxx
1


 
1
HttpClient client = HttpClient.newHttpClient();
2
   
3
HttpRequest request = HttpRequest.newBuilder()
4
  .uri(URI.create("https://reqres.in/api/users/2"))
5
  .build();



We'll look at how to handle different types of response bodies in the following sections.

Handling a Response Body as a String

Handling a body response as a string can be accomplished using BodyHandlers.ofString(), as shown in the following snippet of code:

Java


For specifying a charset, call ofString(String s, Charset charset) .

Handling a Response Body as a File

Handling a body response as a file can be accomplished using BodyHandlers.ofFile(), as shown in the following snippet of code:

Java
 


For specifying the open options, call ofFile(Path file, OpenOption... openOptions) .

Handling a Response Body as a Byte Array

Handling a body response as a byte array can be accomplished using BodyHandlers.ofByteArray(), as shown in the following snippet of code:

Java
 


For consuming the byte array, call ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer) .

Handling a Response Body as an Input Stream

Handling a body response as InputStream can be accomplished using BodyHandlers.ofInputStream(), as shown in the following snippet of code:

Java
 


Handling a Response Body as a Stream of Strings

Handling a body response as a stream of strings can be accomplished using BodyHandlers.ofLines(), as shown in the following snippet of code:

Java


All the above examples can be found on GitHub.

If you enjoyed this article, then I'm sure you will love my book, Java Coding Problems, which has an entire chapter dedicated to HTTP Client API. Check it out!

Topics:
api ,body ,http ,java ,network ,request ,response

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}