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

tre*_*ker 9 html java cookies post facebook

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

到目前为止我有以下代码将home 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();
    }
Run Code Online (Sandbox Code Playgroud)

}

更新:

我已经使用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)
Run Code Online (Sandbox Code Playgroud)

有谁知道这是为什么?

    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();
Run Code Online (Sandbox Code Playgroud)

小智 13

您的代码中存在一些问题

  1. login_form不是表单名称,而是表单ID
  2. 提交按钮值i Log In
  3. 密码字段的类型是 HtmlPasswordInput

所以:

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("jon@jon.com");
final HtmlPasswordInput textField2 = form.getInputByName("pass");
textField2.setValueAttribute("ahhhh");
final HtmlPage page2 = button.click();
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 12

你应该看看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();
Run Code Online (Sandbox Code Playgroud)

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