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();