首页 文章

使用Jsoup检索sessionId cookie的问题

提问于
浏览
0

我'm to write a Java program, which in part, parses 200 unique pages that require the user to log in beforehand. I'已使用Chrome的开发者控制台来确定我的特定登录URL(https://r.espn.go.com/members/v3_1/login),验证登录过程是否使用了POST请求,以及我的用户名(用户名)和密码(密码)的表单数据名称 . 当使用this post的作者指定的方法为后续请求检索SESSIONID cookie时,返回的标头差异很大,并且没有返回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的登录服务吗?还是我做了一些根本错误的事情?

谢谢!

1 回答

  • 1

    让HttpClient为您管理cookie / session . 为此发生这种情况

    • 创建一个HttpContext并将其用于您发出的每个请求,以便会话/ cookie管理处于活动状态 .

    • 设置cookie商店

    • 在您在步骤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请求和响应流量 .

相关问题