如何使用 Java 以编程方式登录 Facebook? [英] How to log into Facebook programmatically using Java?

查看:26
本文介绍了如何使用 Java 以编程方式登录 Facebook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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 + "
";
        }
        System.out.println(allInput);

        in.close();
    }

}

更新:

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

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

推荐答案

你应该看看 HTMLUnit,它比使用上面的要简单得多.以下页面和代码应为您提供指导:

You should take a look at HTMLUnit, it'll be much simpler than using the above. The following page and code should guide you:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆