0

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

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

4

1 回答 1

0

最有可能的问题是您似乎认为您的方法 ( 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;
}
于 2011-12-28T22:55:30.810 回答