44

I'm connecting to a remote server with apache http client. the remote server sends a redirect, and i want to achieve that my client isn't following the redirect automatically so that i can extract the propper header and do whatever i want with the target.

i'm looking for a simple working code sample (copy paste) that stops the automatic redirect following behaviour.

i found Preventing HttpClient 4 from following redirect, but it seems i'm too stupid to implement it with HttpClient 4.0 (GA)

Community
  • 1
  • 1
Chris
  • 15,429
  • 19
  • 72
  • 74

10 Answers10

49

The magic, thanks to macbirdie , is:

params.setParameter("http.protocol.handle-redirects",false);

Imports are left out, here's a copy paste sample:

HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();

// HTTP parameters stores header etc.
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.handle-redirects",false);

// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();

// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

// connect and receive 
HttpGet httpget = new HttpGet("http://localhost/web/redirect");
httpget.setParams(params);
response = httpclient.execute(httpget, localContext);

// obtain redirect target
Header locationHeader = response.getFirstHeader("location");
if (locationHeader != null) {
    redirectLocation = locationHeader.getValue();
  System.out.println("loaction: " + redirectLocation);
} else {
  // The response is invalid and did not provide the new location for
  // the resource.  Report an error or possibly handle the response
  // like a 404 Not Found error.
}
Community
  • 1
  • 1
Chris
  • 15,429
  • 19
  • 72
  • 74
29

Using HttpClient 4.3 and Fluent:

final String url = "http://...";
final HttpClient client = HttpClientBuilder.create()
    .disableRedirectHandling()
    .build();
final Executor executor = Executor.newInstance(client);
final HttpResponse response = executor.execute(Request.Get(url))
    .returnResponse();
David Riccitelli
  • 7,491
  • 5
  • 42
  • 56
  • Pertinent information: `HttpClientBuilder.create().disableRedirectHandling().build();` – Nick Grealy May 06 '16 at 03:43
  • Hey, nice answer. Is there a way to disable redirect for one specific request? It is achievable via request.setParams, but I don't know how to do it in httpclient version after 4.3. – Fan Jin Jul 26 '18 at 17:00
  • 2
    Looking to do the exact same thing as @FanJin. Can someone please provide the answer to his question? – birgersp Jan 15 '19 at 12:15
23

This worked for me:

HttpGet httpGet = new HttpGet("www.google.com");
HttpParams params = httpGet.getParams();
params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
httpGet.setParams(params);
Caner
  • 57,267
  • 35
  • 174
  • 180
16

The default HttpClient implementation is pretty limited in configurability, but you can control the redirect handling by using HttpClient's boolean parameter http.protocol.handle-redirects.

See the docs for reference.

TheWestIsThe...
  • 442
  • 4
  • 14
macbirdie
  • 16,086
  • 6
  • 47
  • 54
  • 2
    a simple example of this [can be found here](http://www.baeldung.com/httpclient-stop-follow-redirect) – TheWestIsThe... Jun 09 '14 at 12:49
  • As of 4.3 this answer is deprecated, use use answer by David Riccitelli – DSchmidt Jun 26 '16 at 09:50
  • @DSchmidt, the new API configures the entire client with this redirect behavior – not just the individual request. I want my client to disable an individual request, and it is achievable via pre 4.3 API. – Fan Jin Jul 26 '18 at 17:02
  • not this, but answer of David Riticelli is the current (>= 4.3) proper solution: https://stackoverflow.com/a/21560006/1915920 – Andreas Covidiot Jun 22 '20 at 12:48
12

Rather than use the property directly you can use:

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
David Koski
  • 965
  • 7
  • 12
2

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

Fan Jin
  • 2,412
  • 17
  • 25
1

this worked for me CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build()

Andreas Covidiot
  • 4,286
  • 5
  • 51
  • 96
Pravin Bansal
  • 4,315
  • 1
  • 28
  • 19
0

To avoid automatic redirection header, one must first configure the request to not do automatic redirects. You can do this by calling HttPClientParams.setRedirection and set it to false. Code snippet is shown below:

HttpPost postURL = new HttpPost(resourceURL);
...
HttpClientParams.setRedirecting(postURL.getParams(), false);
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
0

instead of call HttpClientBuilder directly, you can use

HttpClients.custom().disableRedirectHandling().build();
0
GetMethod method = new GetMethod(url);
method.setFollowRedirects(false); 
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • at least in v4.5.2 there is no `GetMethod` anymore, but it was there in v3: https://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/GetMethod.html – Andreas Covidiot Jun 22 '20 at 12:44