apache HttpClient to access facebook

后端 未结 3 1083
情书的邮戳
情书的邮戳 2020-12-21 08:30

Any examples, tips, guidance for the following scenario?

I have used Apache HttpClient to simulate the functionality of browser to access facebook through java appli

相关标签:
3条回答
  • 2020-12-21 08:53

    Have you taken a look at HtmlUnit. It wraps the HttpClient to create a headless Java browser, with javaScript execution. This way you are not trying to hack the individual forms all the time.

    0 讨论(0)
  • 2020-12-21 08:54

    Perhaps you should use a tool, such as Selenium

    0 讨论(0)
  • 2020-12-21 08:59

    The following code, based on that sample, worked for me:

    DefaultHttpClient httpclient = new DefaultHttpClient();
    
    HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
    
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    
    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();
    }
    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }
    
    HttpPost httpost = new HttpPost("http://www.facebook.com/login.php");
    
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("email", "******"));
    nvps.add(new BasicNameValuePair("pass", "*******"));
    
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    
    response = httpclient.execute(httpost);
    entity = response.getEntity();
    System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
    
    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();
    }
    
    System.out.println("Post logon cookies:");
    cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }
    
    httpclient.getConnectionManager().shutdown();  
    

    I am not sure if your code was managing properly cookies (and session id kept within one of them), maybe that was the problem. Hope this will help you.

    Just to make clear version issue: I was using HttpClient version 4.X, not the old one (3.X). They differ significantly.

    0 讨论(0)
提交回复
热议问题