Apache HttpClient会话不起作用 [英] Apache HttpClient Session not working

查看:129
本文介绍了Apache HttpClient会话不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to log in to a web app on behalf of a user with HttpClient 4.3.3 in the following way:

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中有很多链接,因此我使用了正则表达式并将其中一个拉出.然后我这样做:

...and that's fine. The result I get back is the HTML for the web app menu, so I'm successfully logged in. There's lots of links in the HTML, so I use a regex and pull one of them out. Then I do this:

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.就像Cookie无效一样.在尝试进行后续的GET请求之前,我尝试过重新初始化http客户端,但这没有什么不同.这里有我想念的东西吗?

Now instead of getting the intended HTML from response, I just get the HTML for a "User not logged in" page. It's like the cookies aren't working. I've tried re-initializing the http client before making the subsequent GET request, but it doesn't make a difference. Is there something I'm missing here?

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

Also, after the first request (the login POST), the CookieStore object has cookies, as shown using:

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

它显示3个cookie.它们的名称分别是JSESSIONID,TS7181ec和TSd9290f(所有3个都有值).

It shows 3 cookies. They're names are JSESSIONID, TS7181ec and TSd9290f (all 3 have values).

推荐答案

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

Sorry, rookie mistake on my part. No wonder it wasn't working, the second request in my question (the GET, after logging in) wasn't actually passing in the httpContext object that contains the cookies.

这篇关于Apache HttpClient会话不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆