Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent apache http client from following a redirect

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)

like image 874
Chris Avatar asked Oct 05 '09 10:10

Chris


People also ask

How do you prevent circular redirects?

The only way to truly avoid a circular redirect loop is to fix the server. If you are wondering what is going on (like why it seems to work find in a browser but not from your program), try turning on some of the extra HttpClient logging.

What is LaxRedirectStrategy?

Class LaxRedirectStrategyLax RedirectStrategy implementation that automatically redirects all HEAD, GET, POST, and DELETE requests. This strategy relaxes restrictions on automatic redirection of POST methods imposed by the HTTP specification.

How do I follow curl redirect?

To follow redirect with Curl, use the -L or --location command-line option. This flag tells Curl to resend the request to the new address. When you send a POST request, and the server responds with one of the codes 301, 302, or 303, Curl will make the subsequent request using the GET method.


1 Answers

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. } 
like image 63
Chris Avatar answered Sep 26 '22 20:09

Chris