I have been trying to handle a redirect (302) in java code and I am finally been able to do it. But I am running into a problem. Which is, once the redirect opens a page, clicking any link on the page sends me back to the login page.
So I have to write my own redirect implementation:
private HttpMethod loadHttp302Request(HttpMethod method, HttpClient client, int status, String urlString) throws HttpException, IOException {
if (status != 302)
return null;
String[] url = urlString.split("/");
HttpMethod theMethod = new GetMethod(urlString + method.getResponseHeader("Location")
.getValue());
theMethod.setRequestHeader("Cookie", method.getResponseHeader("Set-Cookie")
.getValue());
theMethod.setRequestHeader("Referrer", url[0] + "//" + url[2]);
theMethod.setDoAuthentication(method.getDoAuthentication());
theMethod.setFollowRedirects(method.getFollowRedirects());
int _status = client.executeMethod(theMethod);
return theMethod;
}
According to my thinking I might not be re-sending or retaining the session cookie. How will I be able to do resend or retain the session cookie? If there are any kinds of mistakes in the above code, please enlighten me.
Any other ideas would be appreciated.
The most likely problem is that you seem to think that the final assignment in your method (
method = theMethod
) has any effect outside ofloadHttp302Request
. (edit: the original code had this statement, but OP changed it later)It doesn't.
Java doesn't have call-by-reference semantics, so that assignment has no net effect. If you want to retain the response (most importantly, the cookie) for a next invocation, you need to return
theMethod
and use that the next time. Something like: