Tuesday, March 28, 2023

10 Examples of New HttpClient + HttpRequest + HttpResponse In Java 11 (REST Client]

Hello guys, one of the notable addition in recent Java release is the full fledged HttpClient from Java. This is one of the class or utility which was much needed in Java. It was quite surprising that JDK doesn't have any fully functional HTTP client to connect to REST APIs in this world of API Integration. Until Java 11, Java developer rely on classes like RestTemplate and WebClient from Spring Framework to make HTTP class to REST APIs, but now you don't need to include Spring Framework in your project just for that. You can now use HttpClient class and its support classes like HttpRequest and HttpResponse to make both synchronous and asynchronous HTTP calls in Java.  

If you are Java veteran like me then you may thinking what about HttpURLConnection? Well, that was there from long time but its not feature rich and use-friendly like RESTTemplate or WebClient.

It doesn't even gives you option to make asynchronous class which is quite important in this age of Microservices and REST API but now you don't need to worry because new HttpClient makes all these possible in Java without using any third party library. 

In this tutorial, we'll explore Java 11's new standardization of HTTP customer API that implements HTTP/ 2 and Web Socket. It aims to replace the old HttpUrlConnection class that has been present in the JDK since the early times of Java.





10 Examples of HttpClient library in Java

Until recently, Java handed only the HttpURLConnection API, which is low- position and is not known for being point-rich and friendly to users. Because of this, some extensively used third-party libraries were generally used, similar as Apache HttpClient, Jetty, and Spring's RestTemplate

Unlike the HttpURLConnection, HTTP Client gives synchronous and asynchronous request mechanisms.

The API includes 3 center classes:

HttpRequest represents the request to be dispatched along the HttpClient.

HttpClient behaves as a box for configuration statistics not an unusual place for more than one request.

HttpResponse represents the end result of an HttpRequest call.

We'll look at each of them in more significant detail within the following sections. First, let's pay attention to a request.

10 Examples of New HttpClient + HttpRequest + HttpResponse In Java (REST Client]



HttpClient Synchronous and Asynchronous Example

Let's first see the Synchronous example from Javadoc of how you can use HttpClient to send a synchronous request:

HttpClient client = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .followRedirects(Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(20))
        .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
        .authenticator(Authenticator.getDefault())
        .build();

HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());

System.out.println(response.body()); 

In this case, your program will send request and wait for response, once response is received it will print the status code and response body

Now, let's see an example of Asynchronous call to a REST API in Java using HttpClient API:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://restres.com/"))
        .timeout(Duration.ofMinutes(2))
        .header("Content-Type", "application/json")
        .POST(BodyPublishers.ofFile(Paths.get("file.json")))
        .build();

client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println); 


If you notice the difference here we have used sendAsync() method instead of send() method in case of previous example. This means, use HttpClient.send() to send a synchronous request and use HttpClient.sendAsync() to make an asynchronous request to any HTTP Server or RESTful Web Service. 

Now, let's see how we can customize HttpRequest class in Java to add timeout, headers and cookie etc. 

1. HttpRequest

HttpRequest is an item that represents the request we need to send. New times may be created with the use of HttpRequest.Builder.  We can get it through calling HttpRequest.newBuilder(). Builder magnificence offers a gaggle of techniques that we will use to configure our request. 
We`ll cover some of the maximum vital ones. 

In JDK 16, there may be a brand new HttpRequest.newBuilder(HttpRequest request, BiPredicate filter) method, which creates a Builder whose preliminary state is copied from an already-present HttpRequest. 



2. How To Set Up a URI

Setting up a URI is actually the first thing you need to do when creating a new request. That is, you need to provide a URL. This can be done in a couple of ways. You can use a constructor for a Builder along with a URI parameter. You can then call uri(URI) on the instance Builder. 

HttpRequest.newBuilder(new URI("https://restres.com/get"))
 
HttpRequest.newBuilder()
           .uri(new URI("https://restres.com/get"))


3. How To Specify The HTTP Method

You can define the HTTP method that will be used by your request. This can be done by calling one of the many methods from Builder. These methods are 
  • GET()
  • POST(BODYPUBLISHER Body)
  • PUT(BODYPUBLISHER Body)
  • DELETE()
It is actually very easy to create a simple GET request.

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .GET()
  .build();

You can see that this request has all the necessary parameters that are required by the new HttpClient. 
It is also possible to add additional parameters to your request. For example, you can add parameters like the version of that particular HTTP Particular, Headers, or a Timeout. 

4. How To Set Up The HTTP Protocol Version in HttpClient in Java

The API can be used to fully leverage the HTTP 2 protocol. It is used by default. But you can also define which version of the protocol you want to use. You can do this by typing the following:

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .version(HttpClient.Version.HTTP_2)
  .GET()
  .build();

It is actually very important to note here that the HttpClient will essentially fall back to HTTP 1.1 if HTTP 2 is not supported.

5. How to Set Up Headers in HttpClient Java

It is also very easy to add headers to your request. This can easily be done by making use of the required Builder methods. You can pass all the headers in the form of key-value pairs into the headers() method. You can also use this method for adding a single key-value header. 

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .headers("key1", "value1", "key2", "value2")
  .GET()
  .build()

HttpRequest request2 = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .header("key1", "value1")
  .header("key2", "value2")
  .GET()
  .build();



6. How To Set Up a Timeout with HttpClient in Java

You can use Timeout for setting the amount of time that you need to wait for a certain response. The HttpTimeoutException will be thrown if the set time expires. By default, it is actually set to infinity. It can also be set with the Duration object by making use of the Timeout() method. 

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .timeout(Duration.of(10, SECONDS))
  .GET()
  .build()

7. How to Set a Request Body using HttpClient in Java

You can add a body to your request by making use of the request builder methods like POST(BodyPublisher body), PUT(BodyPublisher body) and DELETE(). If you do not need a body, you can simply pass an HttpRequest.BodyPublishers.noBody().

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/post"))
  .POST(HttpRequest.BodyPublishers.noBody())
  .build();

8. How To Use The StringBodyPublisher in HttpClient Java

You can set any request body with a BodyPublishers implementation in a very simple and intuitive manner. You can simply pass the String as a Body. Or you can also use the StringBodyPublisher. 
You can create this object with a simple factory method ofString(). This will essentially take a string object as an argument and then create a body. 

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/post"))
  .headers("Content-Type", "text/plain;charset=UTF-8")
  .POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
  .build();

9. How to Use InputStream BodyPublisher in HttpClient in Java

In n Java, you can use the InputStream BodyPublisher in HttpClient to send an HTTP request with the request body obtained from an input stream. The BodyPublishers.ofInputStream() method can be used to create an instance of BodyPublisher from an InputStream.

Here is an example to pass the InputStream as a Supplier. This is actually a bit different from the StringBodyPublishers. 

byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/post"))
  .headers("Content-Type", "text/plain;charset=UTF-8")
  .POST(HttpRequest.BodyPublishers
   .ofInputStream(() -> new ByteArrayInputStream(sampleData)))
  .build();

You can note how you can use a very simple ByteArrayInputStream in this code. You can also use any InputStream implementation. 


10. How to use the ByteArray BodyPublisher in Java HttpClient

BodyPublishers.ofByteArray() is a static factory method in the java.net.http package introduced in Java 11. It returns a HttpRequest.BodyPublisher that publishes the request body as a byte array.

In other words, this method creates a publisher for sending the request body as a byte array. The byte array can be provided as an argument to this method, or it can be generated dynamically at runtime.

Here's an example usage:

byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/post"))
  .headers("Content-Type", "text/plain;charset=UTF-8")
  .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
  .build();

In this example, we create a POST request with a byte array as the request body using BodyPublishers.ofByteArray. We then send the request using HttpClient and print the response body.

HtttpClient Frequently Asked Questions in Java

Here are a couple of common questions Java program ask about HttpClient in Java.

1. What is HttpClient?

It is essentially Java 11's new standardization of HTTP customer API that implements HTTP/ 2 and Web Socket. It aims to replace the heritage HttpUrlConnection class that has been present in the JDK since the early times of Java.

2. What is new about the HttpClient?

Until recently, Java handed only the HttpURLConnection API, which is low- position and is not known for being point-rich and friendly to users. Because of this, some extensively used third-party libraries were generally used, similar as Apache HttpClient, Jetty, and Spring's RestTemplate.

10 Examples of New HttpClient + HttpRequest + HttpResponse In Java (REST Client]



That's all about how to use HttpClient API in Java. It's one of the must know class and utility for Java programmers of all level. Whether you want to download data from a REST API or you want to send data to a RESTful web Service, you can use HttpClient in Java for such thing.

You no longer need any third party library like Apache HttpClient or Spring to make REST API calls in Java. If you liked this list of the 10 best examples of the new HttpClient in Java, feel free to share it with your friends and family.


Other RESTful and REST API articles you may like to explore
  • Why Spring MVC is best to create REST API in Java (article)
  • 5 Best Courses to learn RESTful Web Service using Spring (best courses)
  • Top 10 Java Web service interview questions (see here)
  • Top 10 RESTful web services interview questions for Java developers (see)
  • REST Web Services framework Interview Question (see here)
  • Top 5 Courses to learn Spring MVC (online courses)
  • 10 Free Spring Boot courses for beginners (free courses)
  • 10 REST API Books for Web Developers (books)
  • Difference between SOAP and RESTful web service in Java? (see here)
  • 10 Microservice and Spring courses in Java (online courses)
  • What are idempotent and safe methods of HTTP and REST? (answer)
  • What is the purpose of different HTTP methods in REST? (answer)
  • 5 Books to prepare Java EE interviews (list)
  • 5 courses to learn Spring framework in depth (courses)
  • Top 5 Books to Learn REST and RESTful Web Services? (books)
  • 10 Best Courses to learn Spring Framework (best courses)
  • Top 5 Courses to learn RESTFul Web Services in Java (courses)

P. S. - If you are looking for online training to learn how to develop RESTful Web Services in Java using the Spring framework, I suggest you joining Eugen Paraschiv's REST with Spring course. The course has various options depending upon your experience level and how much you want to learn like beginner's class, intermediate class, and master class. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.