Updated June 21, 2023
Definition of Java HTTP Client
Java HTTP client is used to create the HTTP requests. We need to develop simple get and post requests when creating an HTTP request. Java 11 introduced a new feature of the library of HttpClient. The user is using a third-party library such as HttpClient. In Java new version of the HTTP client is designed to improve the performance while sending requests by the client.
Key Takeaways
- In Java, the HTTP client request and the response body are exposed by using reactive streams. The HTTP client is a subscriber of the request body.
- The interface of the body hander will allow us to inspect the response code before the actual response body is received.
Introduction to Java HTTP Client
In the Java HTTP client, the request and response from the server are achieved by using change numbers such as header compression, push promises, and stream multiplexing. In Java 11, the API is asynchronous. Call of asynchronous is implemented using the completable feature; implementation of this feature takes care while applying every stage once we have finished the previous stage, so we can say that all flow is asynchronous.
The new HTTP client, API, provides a way to perform network operations of HTTP using the support of modern HTTP web sockets. This core class of Java is introducing new functionality. We are implementing the web socket in Java by using the HTTP client. This protocol is very important in Java while creating web sockets.
How to Create a Java HTTP Client?
From Java 11, the HTTP client is standard; we recommended using HTTP client API, as it contains a number of features compared to the Apache API of the HTTP client.
Below are the steps to create the HTTP client in Java as follows:
- In the first step, we need to create the HTTP client instance by using HttpClient.newBuilder() instance.
- In the second step, we need to create the instance of HttpRequest by using HttpRequest.newBuilder() instance.
- In the third step, we request by using httpClient.send() and the response object.
When creating a Java HTTP client, we need to import the package of IOException, net.URI, HttpClient, HttpRequest, HttpResponse, and duration.
Example #1
In the below example, we are creating the Java HTTP client as follows. We are creating the class name as http_client. We are defining the URI of google for sending and getting requests from the URI of google. We are also printing the following status code, body, and headers for the response.
Code:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class http_client {
public static void main(String[] args) {
HttpClient hc = HttpClient.newBuilder ()
.version(HttpClient.Version.HTTP_2)
.connectTimeout (Duration.ofSeconds (10))
.build ();
try {
HttpRequest req = HttpRequest.newBuilder ()
.GET ()
.uri (URI.create ("https://www.google.com"))
.build ();
HttpResponse<String> res = hc.send (req,
HttpResponse.BodyHandlers.ofString ());
System.out.println ("Code: " + res.statusCode ());
System.out.println ("Headers: " + res.headers ().allValues ("type"));
System.out.println ("Body: " + res.body ());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Example #2
In the below example, we are creating it by using Facebook URI. We can see that it will give the same status code as follows.
Code:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class http_client
{
public static void main(String[] args)
{
HttpClient hc = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds (10))
.build();
try {
HttpRequest req = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.facebook.com"))
.build();
HttpResponse<String> res = hc.send(req,
HttpResponse.BodyHandlers.ofString());
System.out.println ("Code: " + res.statusCode ());
System.out.println ("Headers: " + res.headers().allValues("type"));
System.out.println ("Body: " + res.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Java HTTP Client API
We use HTTP client API for sending requests and retrieving responses. We are creating an HTTP client by using builder; we are using builder for configuring the client state. HTTP client provides information on the configuration of resource sharing for all the requests which we have sent. A body handler is supplied for every HTTP request that we have sent. It will know how to handle the response body when receiving the HTTP response.
We can send HTTP requests either asynchronously or synchronously.
Example #1
The below example shows how we can send the HTTP client API synchronously as follows:
Code:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class http_client {
public static void main(String[] args) {
HttpClient hc = HttpClient.newBuilder()
.version (HttpClient.Version.HTTP_2)
.connectTimeout (Duration.ofSeconds(15))
.build();
try {
HttpRequest req = HttpRequest.newBuilder ()
.GET()
.uri(URI.create("https://www.example.com"))
.build();
HttpResponse<String> res = hc.send(req,
HttpResponse.BodyHandlers.ofString ());
System.out.println ("Code: " + res.statusCode ());
System.out.println ("Body: " + res.body ());
} catch (IOException | InterruptedException e) {
e.printStackTrace ();
}
}
}
Example #2
The example below shows how we can send the HTTP client API synchronously. We are sending an asynchronous API request.
Code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import java.time.Duration;
public class http_client {
public static void main(String[] args) throws FileNotFoundException {
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.timeout(Duration.ofMinutes(20))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(req, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
System.out.println ("Code: " + ((HttpResponse) req).statusCode ());
System.out.println ("Body: " + ((HttpResponse) req).body ());
}
}
Examples of Java HTTP Client
Given below are the examples mentioned:
Example #1
Below example shows to get the request to print the response body as a string as follows.
Code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import java.time.Duration;
public class http_client {
public static void main(String[] args) {
HttpClient client1 = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/"))
.build();
client1.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}
Example #2
In the example below, we are creating the client, and the builder configures the client state. Also, we are creating the HTTP request from its builder as follows.
Code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import java.time.Duration;
public class http_client {
public static void main(String[] args) {
HttpClient hc = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
try {
HttpRequest req = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.example.com"))
.build();
HttpResponse<String> res = hc.send(req,
HttpResponse.BodyHandlers.ofString());
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
}
}
After creating a client request, we send the data using synchronous API. We are using the same client and response request.
Code:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import java.time.Duration;
public class http_client
{
public static void main(String[] args)
{
HttpClient hc = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
try {
HttpRequest req = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.example.com"))
.build();
HttpResponse<String> res = hc.send(req,
HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode());
System.out.println(res.body());
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Example #3
In the example below, we are creating the HTTP request as follows.
Code:
HttpClient client1 = HttpClient.newHttpClient ();
After creating the http request, now in this step, we are setting the URL. In the below example, we are using example.com URL.
Code:
HttpRequest.newBuilder(new URI("https://example.com/get"));
HttpRequest.newBuilder().uri(new URI("https://example.com/get"));
After setting up the URL, we need to specify the HTTP method. HTTP is calling the method.
Code:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://example.com/get"))
.GET()
.build();
After specifying the method, we need to specify the protocol version of http. In the below example, we are using version 2 as follows.
Code:
HttpRequest request1 = HttpRequest.newBuilder()
.uri(new URI("https://example.com/get"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
After defining the protocol version, we need to set the headers of the Java http client as follows.
Code:
HttpRequest request2 = HttpRequest.newBuilder()
.uri(new URI("https://example.com/get"))
.headers("key1", "val1", "key2", "val2")
.GET()
.build();
After defining the header, we need to set the timeout. In the below example, we are setting the timeout as 10.
Code:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://example.com/get"))
.timeout (Duration.of(10, SECONDS))
.GET()
.build();
After setting the timeout, we can also set the request body. In the below example, we are adding the body request as follows.
Code:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://example.com/post"))
.POST(HttpRequest.BodyPublishers.noBody())
.build();
After adding the request body, we must also set the handling response body as follows.
Code:
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects (HttpClient.Redirect.ALWAYS)
.build()
.send(request, BodyHandlers.ofString());
After setting the body handling response, we must set the URI response object as follows.
Code:
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
HttpHeaders responseHeaders = response.headers ();
In the below example, we are creating the http client as follows. We are defining the timeout as 15.
Code:
public class http_client {
public static void main(String[] args) {
HttpClient hc = HttpClient.newBuilder ()
.version(HttpClient.Version.HTTP_2)
.connectTimeout (Duration.ofSeconds (15))
.build ();
try {
HttpRequest req = HttpRequest.newBuilder ()
.GET ()
.uri (URI.create ("https://www.google.com"))
.build ();
HttpResponse<String> res = hc.send (req,
HttpResponse.BodyHandlers.ofString ());
System.out.println ("Code: " + res.statusCode ());
System.out.println ("Headers: " + res.headers ().allValues ("type"));
System.out.println ("Body: " + res.body ());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Conclusion
The new HTTP client API provides a way to perform network operations of HTTP using modern HTTP web sockets. This core class of Java is introducing new functionality. It is used to create HTTP requests; when creating an HTTP request, we need to create simple get and post requests.
Recommended Articles
We hope that this EDUCBA information on “Java HTTP Client” was beneficial to you. You can view EDUCBA’s recommended articles for more information.