Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log into Facebook programmatically using Java?

I'm trying to write a Java program that can automatically log into Facebook.

I've got the below code so far that downloads the home html page into a String but don't know how to send the email and password to log into Facebook? Also will the Java program need to handle cookies returned to remain logged in?

public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.facebook.com/");
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc
                .getInputStream()));
        String inputLine;
        String allInput = "";

        while ((inputLine = in.readLine()) != null) {

            allInput += inputLine + "\r\n";
        }
        System.out.println(allInput);

        in.close();
    }

}

Update:

I've tried the below code using htmlUnit however I get the following exception:

Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException:     elementName=[form] attributeName=[name] attributeValue=[login_form] at com.gargoylesoftware.htmlunit.html.HtmlPage.getFormByName(HtmlPage.java:588)

Anyone know why this is?

    final WebClient webClient = new WebClient();
    final HtmlPage page1 = webClient.getPage("http://www.facebook.com");
    final HtmlForm form = page1.getFormByName("login_form");

    final HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByValue("Login").get(0);
    final HtmlTextInput textField = form.getInputByName("email");
    textField.setValueAttribute("[email protected]");
    final HtmlTextInput textField2 = form.getInputByName("pass");
    textField2.setValueAttribute("ahhhh");
    final HtmlPage page2 = button.click();
like image 547
tree-hacker Avatar asked Feb 17 '10 23:02

tree-hacker


1 Answers

There are some problems in your code

  1. is that login_form is not the form name but the form ID
  2. the submit button value i Log In
  3. type of password field is HtmlPasswordInput

so:

final WebClient webClient = new WebClient();
final HtmlPage page1 = webClient.getPage("http://www.facebook.com");
final HtmlForm form = (HtmlForm) page1.getElementById("login_form");

final HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByValue("Log In").get(0);
final HtmlTextInput textField = form.getInputByName("email");
textField.setValueAttribute("[email protected]");
final HtmlPasswordInput textField2 = form.getInputByName("pass");
textField2.setValueAttribute("ahhhh");
final HtmlPage page2 = button.click();
like image 115
Luca Avatar answered Oct 06 '22 18:10

Luca