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

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

问题描述

我试图写一个可以自动登录Facebook的Java程序。

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

到目前为止,我已经得到了下面的代码,将home html页面下载到a String但不知道如何发送电子邮件和密码登录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 + "\r\n";
        }
        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天全站免登陆