如何使用Java以编程方式登录Facebook?

我正在尝试编写一个可以自动登录Facebook的Java程序。

到目前为止,我已经获得了下面的代码,可以将主页html页面下载到String中,但是不知道如何发送电子邮件和密码来登录Facebook?Java程序还需要处理返回的Cookie才能保持登录状态吗?

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

}

}

我已经使用htmlUnit尝试了以下代码,但是出现以下异常:

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)

有人知道为什么吗?

    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("jon@jon.com");

final HtmlTextInput textField2 = form.getInputByName("pass");

textField2.setValueAttribute("ahhhh");

final HtmlPage page2 = button.click();

回答:

您应该看一下HTMLUnit,它比使用上面的要简单得多。以下页面和代码将指导您:

final WebClient webClient = new WebClient();

final HtmlPage page1 = webClient.getPage("http://www.facebook.com");

final HtmlForm form = page1.getFormByName("login_form");

final HtmlSubmitInput button = form.getInputsByValue("Log in");

final HtmlTextInput textField = form.getInputByName("email");

textField.setValueAttribute("jon@jon.com");

final HtmlTextInput textField = form.getInputByName("pass");

textField.setValueAttribute("ahhhh");

final HtmlPage page2 = button.click();

http://htmlunit.sourceforge.net/gettingStarted.html

以上是 如何使用Java以编程方式登录Facebook? 的全部内容, 来源链接: utcz.com/qa/416814.html

回到顶部