DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Next Evolution of Java: Faster Innovation, Simpler Adoption
  • Build a Java Backend That Connects With Salesforce
  • From APIs to Event-Driven Systems: Modern Java Backend Design
  • Jakarta EE Glossary: The Terms Every Java Engineer Should Actually Understand

Trending

  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Java in a Container: Efficient Development and Deployment With Docker
  • The Agent Protocol Stack: MCP vs. A2A vs. AG-UI
  • Liquibase: Database Change Management and Automated Deployments
  1. DZone
  2. Coding
  3. Java
  4. JDK 11 HTTP Client API - Handling Request/Response Body Types

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

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Updated Apr. 06, 20 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
34.2K Views

Join the DZone community and get the full member experience.

Join For Free

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
x
 
1
HttpRequest requestBodyOfByteArray = HttpRequest.newBuilder()
2
  .header("Content-Type", "application/json")
3
  .POST(HttpRequest.BodyPublishers.ofByteArray(
4
    Files.readAllBytes(Path.of("user.json"))))
5
  .uri(URI.create("https://reqres.in/api/users"))
6
  .build();


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
xxxxxxxxxx
1
 
1
HttpRequest requestBodyOfFile = HttpRequest.newBuilder()
2
  .header("Content-Type", "application/json")
3
  .POST(HttpRequest.BodyPublishers.ofFile(Path.of("user.json")))
4
  .uri(URI.create("https://reqres.in/api/users"))
5
  .build();


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
xxxxxxxxxx
1
 
1
HttpResponse<String> responseOfString
2
   = client.send(request, HttpResponse.BodyHandlers.ofString());
3
   
4
System.out.println("Status code: " + responseOfString.statusCode());
5
System.out.println("Body: " + responseOfString.body());


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
 
xxxxxxxxxx
1
 
1
HttpResponse<Path> responseOfFile = client.send(
2
  request, HttpResponse.BodyHandlers.ofFile(
3
    Path.of("response.json")));
4
   
5
System.out.println("Status code: " + responseOfFile.statusCode());
6
System.out.println("Body: " + responseOfFile.body());


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
 
xxxxxxxxxx
1
 
1
HttpResponse<byte[]> responseOfByteArray = client.send(
2
  request, HttpResponse.BodyHandlers.ofByteArray());
3
  
4
System.out.println("Status code: "
5
  + responseOfByteArray.statusCode());
6
System.out.println("Body: "
7
  + new String(responseOfByteArray.body()));


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
 
xxxxxxxxxx
1
14
 
1
HttpResponse<InputStream> responseOfInputStream = client.send(
2
  request, HttpResponse.BodyHandlers.ofInputStream());
3
  
4
System.out.println("\nHttpResponse.BodyHandlers.ofInputStream():");
5
System.out.println("Status code: "
6
   + responseOfInputStream.statusCode());
7
   
8
byte[] allBytes;
9
try (InputStream fromIs = responseOfInputStream.body()) {
10
  allBytes = fromIs.readAllBytes();
11
}
12
  
13
System.out.println("Body: "
14
   + new String(allBytes, StandardCharsets.UTF_8));


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
xxxxxxxxxx
1
 
1
HttpResponse<Stream<String>> responseOfLines = client.send(
2
  request, HttpResponse.BodyHandlers.ofLines());
3
  
4
System.out.println("Status code: " + responseOfLines.statusCode());
5
System.out.println("Body: " + responseOfLines.body().collect(toList()));


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!

Java (programming language) API Java Development Kit

Opinions expressed by DZone contributors are their own.

Related

  • The Next Evolution of Java: Faster Innovation, Simpler Adoption
  • Build a Java Backend That Connects With Salesforce
  • From APIs to Event-Driven Systems: Modern Java Backend Design
  • Jakarta EE Glossary: The Terms Every Java Engineer Should Actually Understand

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook