java - 在 HttpClient 中保留 session

标签 java android cookies web-scraping httpclient

我正在尝试登录网站。在我的第一个请求中,我使用用户名和密码在登录页面上执行 POST 并成功登录。使用相同的 HttpClient 实例,我在网站的不同页面上进行了第二次请求,这次是 GET 请求,但是这次返回的页面未登录。我认为这是由于第二次请求正在新 session 中完成。

在第一个请求之后,在它返回的许多 cookie 中,这是 session ID cookie:

name: ASPSESSIONIDSCSCSBCS
value: GBAJALJBOGKBFLAELPNKEDOE

在第二次请求之后,在许多其他 cookie 中,我有两个不同的 session ID cookie:

name: ASPSESSIONIDSCSCSBCS
value: GBAJALJBOGKBFLAELPNKEDOE

name: ASPSESSIONIDSCSCSBCS
value: MBAJALJBDBOKPEHNCDDFOCBC

我假设因为在第二次请求期间 session ID 不同,它会忽略具有第一个 session ID 的 cookie。

我该如何解决这个问题?

编辑:这是我的代码

public HttpClient httpclient = new DefaultHttpClient();
public CookieStore cookieStore = new BasicCookieStore();
public HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

//The first request 
 HttpPost httppost = new HttpPost("http://www.deeproute.com/deeproute/default.asp");
 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 nameValuePairs.add(new BasicNameValuePair("cookieexists","false"));
 nameValuePairs.add(new BasicNameValuePair("name", mUser));
 nameValuePairs.add(new BasicNameValuePair("password", mPassword));
 nameValuePairs.add(new BasicNameValuePair("subbera", "Login"));

 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 res = httpclient.execute(httppost, localContext);

//The second request
 HttpGet rosterGet = new HttpGet("http://deeproute.com/deeproute/?sel=rosterlook&myleagueno=6&myteamno=12");
 res = httpclient.execute(rosterGet, localContext);

最佳答案

我认为你应该用覆盖cookieStore

 cookieStore = (BasicCookieStore) httpClient.getCookieStore();

只有在登录成功之后..
在那之后我认为你应该用新的 cookieStore 重新设置 Context..
让我知道!

关于java - 在 HttpClient 中保留 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256961/

相关文章:

javascript - 可以检测浏览器中是否允许特定的第三方 cookie?

java - 如何在java项目中提取PE-Header信息?

java - jwrapper online Windows 因 https updateurl 失败

java - 仅使用字符串的动态类加载

android - 在循环中使用媒体播放器播放声音时,循环中有一些暂停,这对我们的用户来说很烦人

c# - .Net cookie 不断返回,过期时间为零

java - 使用RMI以本地模式连接JMX(无端口)

android - 从 arraylist 中删除数据时,Recyclerview 没有正确更新行?

android - 如何从sqlite数据库中获取时间戳值?

javascript - 在 AngularJS 中获取 JSESSIONID 值并创建 Cookie