【问题标题】:How to re-send or retain a session cookie如何重新发送或保留会话 cookie
【发布时间】:2012-01-29 12:35:26
【问题描述】:

我一直在尝试在 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?以上代码如有错误,请赐教。

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

【问题讨论】:

  • 为了增加您在此处获得响应的机会,请确保您的代码格式正确,并删除对阅读代码的人来说毫无意义的内容(例如过多的调试语句)。我刚刚为您完成了上述操作。
  • 非常感谢..下次我会全力以赴的。

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


【解决方案1】:

最可能的问题是您似乎认为您的方法中的最终分配 (method = theMethod) 在loadHttp302Request 之外有任何影响。 (编辑:原代码有这个说法,后来OP改了)

没有。

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

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

【讨论】:

  • 感谢您的回答,但请在提交答案之前检查代码。
  • 你在我的回复之间改变了它。现在你返回HttpMethod,问题解决了吗?
  • 不。仍然在同一页面上...重定向有效,但正如我之前所说,一旦单击页面中的任何链接,它就会将我发送回登录...
猜你喜欢
  • 2019-12-17
  • 2017-04-11
  • 2012-02-26
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2018-01-08
相关资源
最近更新 更多