【问题标题】:How to Handle the Session in Apache HttpClient 4.1如何在 Apache HttpClient 4.1 中处理会话
【发布时间】:2011-09-10 11:35:40
【问题描述】:

我正在使用 HttpClient 4.1.1 来测试我的服务器的 REST API。

我可以设法登录似乎工作正常,但当我尝试做任何其他事情时我失败了。

很可能我在下一个请求中设置 cookie 时遇到了问题。

这是我目前的代码:

HttpGet httpGet = new HttpGet(<my server login URL>);
httpResponse = httpClient.execute(httpGet)
sessionID = httpResponse.getFirstHeader("Set-Cookie").getValue();
httpGet.addHeader("Cookie", sessionID);
httpClient.execute(httpGet);

有没有更好的方法来管理 HttpClient 包中的 session/cookies 设置?

【问题讨论】:

    标签: java session cookies httpclient


    【解决方案1】:

    正确的方法是准备一个CookieStore,您需要在HttpContext 中设置它,然后在每个HttpClient#execute() 调用中传递它。

    HttpClient httpClient = new DefaultHttpClient();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    // ...
    
    HttpResponse response1 = httpClient.execute(method1, httpContext);
    // ...
    
    HttpResponse response2 = httpClient.execute(method2, httpContext);
    // ...
    

    【讨论】:

    • 如果会话过期怎么办?
    • @Ankur,通常服务器会注意到会话已过期并将您重定向到登录页面。如果您的请求是只读的,它会在成功认证后将您重定向到该页面,但如果它是可变的,您将不得不再次这样做。
    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多