I'm connecting to my AppEngine application using the Apache HttpComponents library. In order to authenticate my users, I need to pass an authentication token along to the application's login address (http://myapp.appspot.com/_ah/login?auth=...) and grab a cookie from the header of the response. However, the login page responds with a redirect status code, and I don't know how to stop HttpClient from following the redirect, thus thwarting me from intercepting the cookie.
Fwiw, the actual method I use to send the request is below.
private void execute(HttpClient client, HttpRequestBase method) {
// Set up an error handler
BasicHttpResponse errorResponse = new BasicHttpResponse(
new ProtocolVersion("HTTP_ERROR", 1, 1), 500, "ERROR");
try {
// Call HttpClient execute
client.execute(method, this.responseHandler);
} catch (Exception e) {
errorResponse.setReasonPhrase(e.getMessage());
try {
this.responseHandler.handleResponse(errorResponse);
} catch (Exception ex) {
// log and/or handle
}
}
}
How would I stop the client from following the redirect?
Thanks.
Update:
As per the solution below, I did the following after creating a DefaultHttpClient client
(and before passing it to the execute
method):
if (!this.followRedirect) {
client.setRedirectHandler(new RedirectHandler() {
public URI getLocationURI(HttpResponse response,
HttpContext context) throws ProtocolException {
return null;
}
public boolean isRedirectRequested(HttpResponse response,
HttpContext context) {
return false;
}
});
}
More verbose than it seems it needs to be, but not as difficult as I thought.
A circular redirect is created by making a page redirect to itself, or to a page that redirects to itself, or making two pages redirect to each other... you get the gist.
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
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.
You can do it with the http params:
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
The method has no javadoc, but if you look at the source you can see it sets:
HANDLE_REDIRECTS
which controls:
Defines whether redirects should be handled automatically
With the Version 4.3.x of HttpClient its directly in the clientBuilder.
so when u build your Client use:
CloseableHttpClient client = clientBuilder.disableRedirectHandling().build();
I know its an old question but I had this problem too and want to share my solution.
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