通过Java URLConnection登录Facebook

3
我正在编写一个Java应用程序,希望能够登录并查看我的墙(只有我的墙)和一些群组,以查看是否有新的发布内容。这不是生产代码,仅供我个人使用。问题在于我无法弄清楚如何在使用URLConnection时进行登录。如果您没有登录,可以查看Facebook公开的群组。但您必须登录才能查看私人群组,而我也想能够查看私人群组。这不是Web应用程序,只是建立连接并获取html,然后解析其中内容。
我的朋友说Facebook有一个OAuth用于此目的,但在阅读互联网上的信息后,似乎OAuth是用于登录您的应用程序或为客户端验证并可能发布到其墙上。但也许我完全错误地做了这件事,并且应该使用OAuth和Graph API之类的东西...
无论如何,我尝试构建URLConnection并向Facebook发出请求,保存所有Cookie,然后尝试使用所有标头和其他内容构建新的连接以登录Facebook,但它知道这不是实际用户而是自动化程序,并不能正常工作。有人知道我如何能够获得身份验证吗?
String cookies = "";
URL myUrl = new URL("https://www.facebook.com/");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
String headerName=null;
for (int i=1; (headerName = urlConn.getHeaderFieldKey(i))!=null; i++) {
    if (headerName.equals("Set-Cookie")) {                  
       String cookie = urlConn.getHeaderField(i);    
       cookie = cookie.substring(0, cookie.indexOf(";"));
       String cookieName = cookie.substring(0, cookie.indexOf("="));
       String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
       cookies = cookies+cookieName+"="+cookieValue+"; ";
       cookieNameList.add(cookieValue);
    }
}    
URL url = new URL("https://www.facebook.com/login.php?login_attempt=1");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Cookie", cookies);
conn.setRequestProperty("accept-encoding", "gzip,deflate,sdch");
conn.setRequestProperty("accept-language", "en-US,en;q=0.8");
conn.setRequestProperty("cache-control", "max-age=0");
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty("accepts-encoding", "gzip,deflate,sdch");
conn.setRequestProperty("accept-encoding", "gzip,deflate,sdch");
conn.setRequestProperty("accept-encoding", "gzip,deflate,sdch");
String query = "lsd=AVpGDi9X&email=xxxxxxxx%40gmail.com&pass=xxxxxxxxx&persistent=1&default_persistent=1&timezone=360&lgnrnd=135940_imAl&lgnjs=1375995581&locale=en_US";
OutputStream output = null;

try {
    output = conn.getOutputStream();
    output.write(query.getBytes("UTF-8"));
} finally {
     if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
try{
  BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  String line;
  while ((line = rd.readLine()) != null) {
      System.out.println(line);
  }
  rd.close();
}catch(Exception e){
    System.out.print("URL BROKE!");
}
3个回答

0

当你刚开始时,这可能有点令人困惑。我假设你不想自动化输入fb密码到网页中的过程。在这种情况下,你需要使用OAuth来授权你的应用程序访问你的fb账户 - 而无需你的应用程序知道你的fb密码。在这种情况下,你可以从这里开始:

https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/

为了使这个工作正常运行,你的程序要么能够显示一个浏览器窗口,要么你要指示用户访问授权URL,并将令牌结果返回给你的程序。

我稍微更新了一下描述。这不是一个网络应用程序或任何东西,这只是一个我从我的计算机上运行的小型Java程序。我正在尝试硬编码我的用户名和密码,这很好。我只想爬取大量Facebook页面以查找关键字。 - Chase Roberts

0

你必须添加这行代码:

conn.setRequestMethod("post");

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接