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 implementation of all these examples and code snippets can be found in the GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

For HttpClient 4.x code snippets, please refer to our HttpClient 4 module.