Let's get started with a Microservice Architecture with Spring Cloud:
Apache HttpClient – Do Not Follow Redirects
Last updated: March 19, 2025
1. Overview
In this article, we’ll learn how to configure the Apache HttpClient to stop following redirects.
By default, following the HTTP Spec, the HttpClient will automatically follow redirects.
For some use cases, that may be perfectly fine, but there are certainly use cases where that’s not desired – and we’ll now look at how to change that default behaviour and stop following redirects.
If you want to dig deeper and learn other cool things you can do with the HttpClient, head over to the main HttpClient tutorial.
2. Do Not Follow Redirects
2.1. Configuration – HttpClient 5
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
final HttpGet request = new HttpGet("http://t.co/I5YYd9tddw");
try (CloseableHttpClient httpClient = HttpClients.custom()
.disableRedirectHandling()
.build()) {
httpClient.execute(request, response -> {
assertThat(response.getCode(), equalTo(301));
return response;
});
}
}
2.1. Configuration – HttpClient 4.5
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient instance = HttpClients.custom().disableRedirectHandling().build();
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
CloseableHttpResponse response = instance.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
3. Conclusion
This quick tutorial covered configuring the Apache HttpClient – to prevent it from following HTTP redirects automatically.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
















