How do I follow redirects using Java 11 HttpClient?

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

  1. followRedirects Option:
    • The followRedirects method accepts one of the HttpClient.Redirect enum values:
      • Redirect.NEVER: Never follows redirects. (Default)
      • Redirect.ALWAYS: Always follows redirects.
      • Redirect.NORMAL: Follows redirects for GET and HEAD requests only.
    • In this example, Redirect.ALWAYS is used, which instructs the client to follow all redirects.
  2. Building the Client:
    • HttpClient is created using its builder (HttpClient.newBuilder()).
  3. Making the Request:
    • An HttpRequest is built specifying the URI.
    • You can set methods (GET, POST, etc.), headers, and request configurations as needed.
  4. Handling the Response:
    • The send method executes the request and waits for the response.
    • Use HttpResponse.BodyHandlers.ofString() to handle the response body as a String.

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 handle 3xx responses manually, which include the Location 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).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.