java - 使用 Jsoup 检索 sessionId cookie 时出现问题

标签 java session-cookies jsoup

我要编写一个 Java 程序,该程序部分地解析 200 个需要用户事先登录的独特页面。我使用 Chrome 的开发者控制台来确定我的特定登录 URL ( https://r.espn.go.com/members/v3_1/login ),验证登录过程是否使用 POST 请求,以及我的用户名 (username) 和密码 (password) 的表单数据名称。当使用this作者指定的方法时post 为后续请求检索 SESSIONID cookie,返回的 header 有很大不同,并且没有返回 cookie。

我还尝试了以下代码片段,它使用 Jsoup 和 Apache 的 HttpClient、HttpPost 和 HttpResponse 返回登录页面:

MultipartEntity entity = new MultipartEntity();
entity.addPart("username", new StringBody(myUsername));
entity.addPart("password", new StringBody(myPassword));

HttpPost post = new HttpPost(url);
post.setEntity(entity);

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);

String html = EntityUtils.toString(response.getEntity());

Document document = Jsoup.parse(html, url);

我读过的每个示例都有一个带有 .php 后缀的登录 URL,此方法是否仅适用于基于 PHP 的登录服务?或者我做的事情根本就是错误的吗?

谢谢!

最佳答案

让 HttpClient 为您管理 cookie/ session 。为了实现这一点

  1. 创建一个 HttpContext 并将其用于您发出的每个请求,以便 session /Cookie 管理处于 Activity 状态。
  2. 设置 Cookie 存储
  3. 在您在第 1 步中创建的上下文中执行每个网络请求

以下是 HttpClient 4.1.x 版本的示例代码。阅读 Section 3.8 HTTP state management and execution context他们的文档。另外,请浏览this thread .

//create the local context to be shared across multiple requests of the same session
HttpContext localContext = new BasicHttpContext(); 

 // Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();

// Bind custom cookie store to the local context
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

// execute the post within the context
HttpResponse response = client.execute(post,localContext);

如果这不能解决问题,则使用wireshark或Fiddler2检查HTTP请求和响应流量。

关于java - 使用 Jsoup 检索 sessionId cookie 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8513671/

相关文章:

java - 强制 Eclipse 忽略 Java 搜索的测试类

java - 将各种 editText 传递给另一个 Activity

asp.net - 跨两个命名域共享 session cookie

android - 使用在 Android 中使用 Jsoup 解析的 html 内容从 webView 中删除链接

java - for循环内的System.arraycopy不是切换矩阵行吗?

java - 从双表生成 UUID

java - 强制 Tomcat 通过 http 使用安全的 JSESSIONID cookie

javascript - 让广告每 5 分钟出现一次?

Java jsoup链接选择

android - 如何在显示到 Android 中的 webview 之前清除 html 页面?