我正在编写一个Java应用程序,希望能够登录并查看我的墙(只有我的墙)和一些群组,以查看是否有新的发布内容。这不是生产代码,仅供我个人使用。问题在于我无法弄清楚如何在使用URLConnection时进行登录。如果您没有登录,可以查看Facebook公开的群组。但您必须登录才能查看私人群组,而我也想能够查看私人群组。这不是Web应用程序,只是建立连接并获取html,然后解析其中内容。
我的朋友说Facebook有一个OAuth用于此目的,但在阅读互联网上的信息后,似乎OAuth是用于登录您的应用程序或为客户端验证并可能发布到其墙上。但也许我完全错误地做了这件事,并且应该使用OAuth和Graph API之类的东西...
无论如何,我尝试构建URLConnection并向Facebook发出请求,保存所有Cookie,然后尝试使用所有标头和其他内容构建新的连接以登录Facebook,但它知道这不是实际用户而是自动化程序,并不能正常工作。有人知道我如何能够获得身份验证吗?
我的朋友说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!");
}