How does HttpClient handle automatic following of HTTP redirects (3xx responses), and how would you configure or disable this behavior?
Short answer
HttpClient.Redirect (configured via HttpClient.newBuilder().followRedirects(policy)) controls redirect-following behavior, with options including NEVER (never automatically follow redirects, giving the caller full control to inspect and manually handle any 3xx response), ALWAYS…
Advertisement
AModel answer
HttpClient.Redirect (configured via HttpClient.newBuilder().followRedirects(policy)) controls redirect-following behavior, with options including NEVER (never automatically follow redirects, giving the caller full control to inspect and manually handle any 3xx response), ALWAYS (always follow redirects regardless of protocol scheme changes, including a potentially security-relevant HTTPS-to-HTTP downgrade), and NORMAL (the sensible default, following redirects except when a redirect would downgrade from HTTPS to plain HTTP, a specific protection against a common security concern) -- understanding and deliberately choosing the appropriate policy matters for both correctness (some APIs use redirects meaningfully) and security (blindly following all redirects unconditionally, including protocol downgrades, can expose sensitive data).
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL) // follows redirects, but refuses HTTPS-to-HTTP downgrades
.build();
// To manually inspect and control redirect handling instead:
HttpClient manualClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NEVER)
.build();
HttpResponse<String> response = manualClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 302) {
String newLocation = response.headers().firstValue("Location").orElseThrow();
// decide explicitly whether/how to follow this redirect
}Real-world example
A security-conscious HTTP client integration deliberately uses the default NORMAL redirect policy (rather than ALWAYS) specifically to ensure a compromised or misconfigured server response can never silently downgrade a sensitive request from HTTPS to unencrypted HTTP through a crafted redirect chain.
Likely follow-ups
- What specific security risk does an HTTPS-to-HTTP redirect downgrade actually create for a client following it automatically?
- How would you detect and log every redirect a request goes through, for debugging or auditing purposes?
Related topics