Sub topic 13
Following redirects
This chapter assumes you can build an HttpClient and send a request with send, as covered in earlier chapters. It explains how the client handles 3xx responses, what the three redirect policies do, and when to follow redirects yourself.
What a redirect is
A server sends a redirect when the resource you asked for lives somewhere else. The response has a 3xx status code and a Location header with the new address. The client is expected to send a new request to that address.
| Status | Meaning | Method on the follow-up request |
|---|---|---|
| 301 | Moved permanently | POST becomes GET, other methods are kept |
| 302 | Found (temporary) | POST becomes GET, other methods are kept |
| 303 | See other | Becomes GET |
| 307 | Temporary redirect | Same method and body |
| 308 | Permanent redirect | Same method and body |
The 301 and 302 rows match browser behavior and the JDK implementation. Because of that behavior, 307 and 308 exist for cases where the method must not change.
The default: no redirects
HttpClient does not follow redirects unless you ask it to. The default policy is Redirect.NEVER. A 301 response then comes back as a normal HttpResponse with status 301, and your code gets no signal that anything is wrong.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class DefaultRedirect {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://github.com/")).build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.headers().firstValue("Location").orElse("(none)"));
}
}If a call returns an empty or surprising body, check the status code first. A 3xx under the default policy is a common cause.
The three policies
You choose a policy on the client builder with followRedirects. It applies to every request sent through that client.
| Policy | Behavior |
|---|---|
| `Redirect.NEVER` | Never follow. This is the default. |
| `Redirect.NORMAL` | Follow, except when the redirect goes from HTTPS to HTTP. |
| `Redirect.ALWAYS` | Follow every redirect, including HTTPS to HTTP. |
NORMAL is the right choice for most programs. The HTTPS-to-HTTP exception stops the client from silently moving a request from an encrypted connection to a plain one. ALWAYS removes that protection, so use it only when you control both ends and understand the risk.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class FollowNormal {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://github.com/"))
.timeout(Duration.ofSeconds(10))
.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("Was redirected: " + response.previousResponse().isPresent());
}
}How the client follows a redirect
When a policy allows it, the client handles the whole chain inside one send call.
Several details follow from this flow:
- A relative
Locationvalue, such as/login, is resolved against the URI of the request that produced it. - The client follows at most 5 redirects per request by default. You can change this with the
jdk.httpclient.redirects.retrylimitsystem property. Exceeding the limit causes anIOException, not a 3xx response, so your existingIOExceptionhandler covers it. response.uri()is the URI of the last request, not the one you built. Use it when you need the final address.response.previousResponse()returns anOptional<HttpResponse<T>>holding the 3xx response that led to this one. You can follow the chain by calling it repeatedly. Intermediate responses have no body (the body is discarded), but their status and headers are available.
Redirects and request bodies
A 307 or 308 redirect asks the client to repeat the request, body included. The client therefore asks the BodyPublisher for the body again. Publishers such as ofString and ofByteArray can be read as many times as needed. A publisher built from a one-shot stream may not be, so a POST through a redirecting endpoint can fail or send an empty body. Prefer replayable publishers for requests that may be redirected.
A 301, 302 or 303 changes a POST into a GET and drops the body. If you POST to an endpoint and the call seems to succeed but your data never arrives, check whether the server answered with one of these codes and the client turned your POST into a GET.
Credentials across redirects
The policy decides only whether to follow, not whether a new host should be trusted. Headers you set on the request, such as Authorization, may be sent again to the redirect target. Behavior can differ between JDK versions, so check it on yours before relying on it. If a redirect might point at another host, for example a download served from a storage service, do not rely on automatic following for authenticated requests. Follow the redirect yourself and decide which headers to send.
Following redirects manually
Use Redirect.NEVER and handle 3xx codes in your own code when you need to inspect each hop, strip credentials, or apply your own limit.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ManualRedirect {
private static final int MAX_HOPS = 3;
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.followRedirects(Redirect.NEVER)
.build();
URI current = URI.create("http://github.com/");
for (int hop = 0; hop <= MAX_HOPS; hop++) {
HttpRequest request = HttpRequest.newBuilder(current).GET().build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status < 300 || status >= 400) {
System.out.println(status + " at " + current);
return;
}
String location = response.headers().firstValue("Location")
.orElseThrow(() -> new IOException("3xx without Location"));
current = current.resolve(location);
System.out.println("Redirect " + status + " -> " + current);
}
throw new IOException("Too many redirects");
}
}URI.resolve handles both absolute and relative Location values. Add your own check on current.getHost() before each hop if you want to refuse redirects to other hosts.
Common mistakes
- Expecting redirects to work with a default client. Set
followRedirectsexplicitly. - Choosing
ALWAYSto "make it work" for an HTTPS-to-HTTP redirect. The fix is usually to request the HTTPS address directly. - Reading the request URI instead of
response.uri()to find where the data came from. - Sending a POST through a 301 or 302 and expecting the body to arrive.
Exercise
Your client uses Redirect.NORMAL. A call to http://api.example.com/v1/items returns status 200, but the body is an HTML login page instead of JSON. What do you check first, and how do you do it in code?
Show answer
Check whether the call was redirected. Print response.uri() to see the final address and response.previousResponse() to see the 3xx response that led to it. Here the server probably redirected to a login page. Fix the cause by requesting the correct URL (usually HTTPS) or by supplying the required credentials.
Exercise
A client built with Redirect.NORMAL sends a POST with a JSON body, and the server answers 303 with a Location header. What request does the client send next, and what happens to the body?
Show answer
It sends a GET to the Location address, and the body is not sent. A 303 always turns the follow-up into a GET. Only 307 and 308 repeat the original method and body.