How to re-send or retain a session cookie

微笑、不失礼 提交于 2019-12-11 15:32:41

问题


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.


回答1:


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)

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:

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


来源:https://stackoverflow.com/questions/8661984/how-to-re-send-or-retain-a-session-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!