views:

1178

answers:

3

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 this question on SO but it seems i'm too stupid to implement it with HttpClient 4.0 (GA)

+2  A: 

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.

macbirdie
+2  A: 

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.
}
Chris
A: 

Rather than use the property directly you can use:

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
David Koski