【问题标题】:Problems using Jsoup to retrieve sessionId cookies使用 Jsoup 检索 sessionId cookie 的问题
【发布时间】:2011-12-15 00:31:54
【问题描述】:

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

我还尝试了以下 sn-p,它同时使用了 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 的登录服务?还是我做错了什么?

谢谢!

【问题讨论】:

    标签: java session-cookies jsoup


    【解决方案1】:

    让 HttpClient 为您管理 cookie/会话。为了发生这种情况

    1. 创建一个 HttpContext 并将其用于您发出的每个请求,以便会话/cookie 管理处于活动状态。
    2. 设置 cookie 存储
    3. 在您在步骤 1 中创建的上下文中执行每个 Web 请求

    以下是 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 请求和响应流量。

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2013-07-02
      • 2018-02-19
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多