【问题标题】:Apache HttpClient Session not workingApache HttpClient 会话不起作用
【发布时间】:2014-04-23 18:03:45
【问题描述】:

我正在尝试通过以下方式代表具有 HttpClient 4.3.3 的用户登录 Web 应用程序:

CloseableHttpClient client = HttpClients.createDefault();
CookieStore cookies = new BasicCookieStore();
HttpPost httpPost = new HttpPost(LOGIN_URL);

List <NameValuePair> paramList = new ArrayList <NameValuePair>();
paramList.add(new BasicNameValuePair("userid", username));
paramList.add(new BasicNameValuePair("pword", password));

httpPost.setEntity(new UrlEncodedFormEntity(paramList));
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies);
CloseableHttpResponse response = client.execute(httpPost, httpContext);

...没关系。我得到的结果是 web 应用程序菜单的 HTML,所以我成功登录。HTML 中有很多链接,所以我使用正则表达式并将其中一个拉出来。然后我这样做:

HttpGet httpGet = new HttpGet(URL_I_PULLED_FROM_HTML);
httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies);
response = client.execute(httpGet);
client.close();

现在我没有从response 获取预期的HTML,而是获取“用户未登录”页面的HTML。就像cookies不工作一样。在发出后续 GET 请求之前,我尝试过重新初始化 http 客户端,但这并没有什么不同。我这里有什么遗漏吗?

此外,在第一个请求(登录 POST)之后,CookieStore 对象具有 cookie,如下所示:

for (Cookie cookie : cookies.getCookies()) {
    LOG.info(cookie.getName());
    LOG.info(cookie.getValue());
}

它显示了 3 个 cookie。它们的名称是 JSESSIONID、TS7181ec 和 TSd9290f(所有 3 个都有值)。

【问题讨论】:

  • 在您的代码 sn-p 中,您实际上似乎没有在任何东西上使用 httpContext ...?你是如何使用它的?
  • 很好,几分钟前我自己才注意到这一点。它现在正在工作。

标签: java session apache-httpclient-4.x


【解决方案1】:

对不起,我的菜鸟错误。难怪它不起作用,我的问题中的第二个请求(登录后的 GET)实际上并没有传入包含 cookie 的 httpContext 对象。

【讨论】:

  • Code sn-p 可能是固定版本?
  • @rogerdpack 抱歉,这对我来说是很久以前的事了,我手头没有那个代码,但我只是忘记在 GET 调用中实际传递 BasicHttpContext,所以它应该是client.execute(httpGet, httpContext);
猜你喜欢
  • 2014-09-29
  • 2012-08-24
  • 2020-10-10
  • 2023-02-16
  • 2011-01-07
  • 2018-10-30
  • 2019-10-16
相关资源
最近更新 更多