Java 11 introduced a new HttpClient
API in the java.net.http
package, making it much easier and more flexible to handle HTTP requests and responses. By default, the HttpClient
does not follow redirects automatically. However, you can configure it to follow redirects if required.
Here’s how you can configure the HttpClient
to follow redirects:
Code Example
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpClient.Redirect;
public class FollowRedirectExample {
public static void main(String[] args) {
try {
// Create the HttpClient and configure it to follow redirects
HttpResponse<String> response;
try (HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(Redirect.ALWAYS) // Configures the client to always follow redirects
.build()) {
// Create an HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/redirect-to?url=https://example.com")) // URL that redirects
.GET() // HTTP GET request
.build();
// Send the request and get the response
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
// Print the status code and body
System.out.println("Response Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation of Key Parts
followRedirects
Option:- The
followRedirects
method accepts one of theHttpClient.Redirect
enum values:Redirect.NEVER
: Never follows redirects. (Default)Redirect.ALWAYS
: Always follows redirects.Redirect.NORMAL
: Follows redirects forGET
andHEAD
requests only.
- In this example,
Redirect.ALWAYS
is used, which instructs the client to follow all redirects.
- The
- Building the Client:
HttpClient
is created using its builder (HttpClient.newBuilder()
).
- Making the Request:
- An
HttpRequest
is built specifying the URI. - You can set methods (
GET
,POST
, etc.), headers, and request configurations as needed.
- An
- Handling the Response:
- The
send
method executes the request and waits for the response. - Use
HttpResponse.BodyHandlers.ofString()
to handle the response body as aString
.
- The
Expected Output
If the redirection succeeds:
Response Status Code: 200
Response Body: <HTML content of https://example.com>
Notes
- If you set
Redirect.NEVER
(the default), you will need to handle3xx
responses manually, which include theLocation
header containing the redirection URL. - If an infinite redirection loop exists, the client may fail. You can control this by setting a timeout using
HttpClient.Builder.connectTimeout(Duration)
.