如何重新发送或保留会话cookie

时间:2011-12-28 22:25:04

标签: java http redirect session-cookies apache-commons-httpclient

我一直在尝试在java代码中处理重定向(302),我终于能够做到了。但我遇到了一个问题。也就是说,一旦重定向打开页面,单击页面上的任何链接都会将我发回登录页面。

所以我必须编写自己的重定向实现:

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;
}

根据我的想法,我可能不会重新发送或保留会话cookie。我如何能够重新发送或保留会话cookie?如果上面的代码有任何错误,请赐教。

任何其他想法将不胜感激。

1 个答案:

答案 0 :(得分:0)

最可能的问题是,您似乎认为方法中的最终作业(method = theMethod)在loadHttp302Request之外有任何影响。 (编辑:原始代码有此声明,但OP稍后更改了它)

没有。

Java没有call-by-reference语义,因此赋值没有净效应。如果要保留下一次调用的响应(最重要的是cookie),则需要返回theMethod并在下次使用时再使用它。类似的东西:

private HttpMethod loadHttp302Request(HttpMethod method, HttpClient client, int status, String urlString) throws HttpException, IOException {
    // code as before
    return theMethod;
}