Catching Post Redirects with HttpClient

For some very good reasons, RFC 2616 and HttpClient do not allow automatic POST redirects. A good reason, but irritating it is nontheless.
I had to get around it today for a bunch of cases which are clear and very common; the case where a POST continues into a GET. For instance; you entered a login/password and are redirected to another page when it is right/wrong without the need for the POST info to be posted to that page also.

The following code has been written for a simple proxy server, so everything is passed to the response;

First of all, you need to know if there is a redirect going on;

method is a PostMethod, request is the HttpServletRequest, response is the HttpServletResponse;

if (request.getMethod().equals(“POST”) && method.getResponseHeader(“location”)!=null) {

Then you don’t need the current method anymore, because you are redirecting;


Get the location to redirect to;

String location = method.getResponseHeader(“location”).getValue();

And make a new GetMethod:

method = new GetMethod(dst+’/’+location);

dst is the destination domain which you know ofcourse, because you cannot use HttpClient without it.

Run the method;

statusCode = client.executeMethod(method);

Make sure the response knows that this is another URL: you can experiment with this to show any URL in the browser of the client:

response.setHeader(“Location”, location);

This works fine for the cases I tried like logging in and filling forms.

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>