Sub topic 12
Following Redirects with `HttpClient`
Assume you know Java 11 syntax, HTTP status codes, headers, and checked exceptions. This chapter focuses on how HttpClient handles a response that sends the client to another URI.
A redirect is an HTTP response that tells the client to try another URI. The response usually contains a Location header. Common redirect status codes include:
301 Moved Permanently302 Found303 See Other307 Temporary Redirect308 Permanent Redirect
Choose a redirect policy
HttpClient does not follow redirects by default. Configure the policy when building the client:
| Policy | Behavior |
|---|---|
| `NEVER` | Never follow redirects. This is the default. |
| `NORMAL` | Follow normal redirects, but do not change from HTTPS to HTTP. |
| `ALWAYS` | Follow redirects, including HTTPS to HTTP. |
NORMAL is usually the safest general choice. Moving from HTTPS to HTTP can expose data because HTTP does not encrypt the connection.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class RedirectExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://httpbin.org/redirect-to?url=https%3A%2F%2Fexample.com%2F"))
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Final status: " + response.statusCode());
System.out.println("Final URI: " + response.uri());
System.out.println(response.body());
}
}With redirects enabled, send returns the response from the final URI. Call response.uri() to see where the request ended. If redirects are disabled, the response contains the original redirect status and its Location header.
Method and security considerations
Redirect handling can affect the request method. For example, HTTP clients commonly turn a 301, 302, or 303 response for a POST into a GET. A 307 or 308 redirect preserves the original method and request body.
This difference matters when a request changes data. A redirected POST may be repeated, changed to a GET, or rejected by the destination. Review the API's redirect behavior before enabling redirects for payment, deletion, or other state-changing requests.
Credentials also require care. A redirect can send a request to a different host. Do not blindly forward secrets such as API keys or bearer tokens to an unfamiliar destination. For sensitive calls, use NEVER, inspect the Location header, and decide explicitly whether the destination is trusted.
Exercise
What policy should you choose when an application must never follow a redirect from HTTPS to HTTP?
Show answer
Use HttpClient.Redirect.NORMAL. It follows ordinary redirects but rejects the HTTPS-to-HTTP downgrade.