apache HttpClient to access facebook

后端 未结 3 1175
情书的邮戳
情书的邮戳 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: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 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  nvps = new ArrayList ();
    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.

提交回复
热议问题