You can create an instance of HttpClient in two ways: by using its static getHttpClient() method, or by using the newBuilder() method (this follows the builder pattern).
The static getHttpClient() method returns a HttpClient instance with basic or default settings, as follows:
HttpClient client = HttpClient.newHttpClient();
To add custom settings, you can use its newBuilder() method, which follows the builder design pattern and calls relevant methods. Let's start with a basic version, and then add to it. For example, you can use the following code to set the HTTP version as 2:
HttpClient client = HttpClient.builder(). .version(Version.HTTP_2) .build();
Often, when you access a resource using a web browser, you see a message stating that the resource has moved to another location and that you are being redirected to the new address. In this case, your web browser receives the new URI. You can accomplish the redirection to the new URI programmatically, by specifying so, through the method followRedirects(). Here's an example:
HttpClient client = HttpClient.builder(). .version(Version.HTTP_2) .followRedirects(Redirect.NORMAL), .build();
The preceding code calls followRedirects(), passing Redirect.NORMAL. Now, Redirect is a nested enum defined in the HttpClient class, with the following constant values:
Enum Value |
Description |
ALWAYS |
Always redirect |
NEVER |
Never redirect |
NORMAL |
Always redirect, except for HTTPS URLs to HTTP URLs |
It's common for a lot of websites to authenticate a user by its registered username and password. You can add the authentication values to HttpClient by using the authenticator() method. The following example uses the default authentication:
HttpClient client = HttpClient.newBuilder(). .version(Version.HTTP_2) .followRedirects(redirect.NORMAL), .authenticator(Authenticator.getDefault()) .build();
The following code uses custom values ("admin" and "adminPassword") for authentication:
HttpClient client = HttpClient.newBuilder().
.version(Version.HTTP_2) .followRedirects(redirect.NORMAL), .authenticator(new Authenticator() { public PasswordAuthentication
getPasswordAuthentication() { return new PasswordAuthentication(
"admin", "adminPassword".toCharArray()); }) .build();
The code snippets in this section demonstrated how to create an instance of HttpClient.