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)
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.
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.
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.
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. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With