Before HttpClient 4.3
In older versions of the Http Client (before 4.3), we can configure what the client does with redirects as follows:
@Test
public void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected()
throws ClientProtocolException, IOException {
DefaultHttpClient instance = new DefaultHttpClient();
HttpParams params = new BasicHttpParams();
params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
// HttpClientParams.setRedirecting(params, false); // alternative
HttpGet httpGet = new HttpGet("http:/testabc.com");
httpGet.setParams(params);
CloseableHttpResponse response = instance.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
Notice the alternative API that can be used to configure the redirect behavior without using setting the actual raw http.protocol.handle-redirects parameter:
HttpClientParams.setRedirecting(params, false);
Also notice that, with follow redirects disabled, we can now check that the Http Response status code is indeed 301 Moved Permanently – as it should be.
After HttpClient 4.3
HttpClient 4.3 introduced a cleaner, more high level API to build and configure the client:
@Test
public void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected()
throws ClientProtocolException, IOException {
HttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
HttpResponse response = instance.execute(new HttpGet("http://testabc.com"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
Note that the new API configures the entire client with this redirect behavior – not just the individual request.
Reference: http://www.baeldung.com/httpclient-stop-follow-redirect