如何使用Java以编程方式登录Facebook?
发布时间:2020-12-15 07:38:06 所属栏目:Java 来源:网络整理
导读:我正在尝试编写一个可以自动登录Facebook的 Java程序. 到目前为止我有以下代码将home html页面下载到String但不知道如何发送电子邮件和密码登录Facebook? Java程序还需要处理返回的cookie以保持登录状态吗? public static void main(String[] args) throws
我正在尝试编写一个可以自动登录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 + "rn"; } 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |