如何重新发送或保留会话cookie [英] How to re-send or retain a session cookie

查看:187
本文介绍了如何重新发送或保留会话cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

最可能的问题是你似乎认为方法中的最终赋值( method = theMethod )有任何 loadHttp302Request 之外的效果。 (编辑:原始代码有此声明,但OP稍后更改了)

The most likely problem is that you seem to think that the final assignment in your method (method = theMethod) has any effect outside of loadHttp302Request. (edit: the original code had this statement, but OP changed it later)

它没有。

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

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:

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

这篇关于如何重新发送或保留会话cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆