Logging into facebook via java URLConnection
I am writing a java application and I want it to be able to login and go
to my wall and a few groups to see if anything new has been posted. The
problem is that I can't figure out how to login while using a
URLConnection. My friend says facebook has a OAuth thing for this purpose
but after reading around the internet it seems like the OAuth is for
logging in your application or for logging in a client and verifying them
and maybe posting to their wall. But maybe I am just doing this the
complete wrong way and should be using oauth and the graph api or
something...
Anyway, I tried building a URLConnection and making a request to facebook,
saving all the cookies, and then tried constructing a new connection with
all the headers and whatnot to login to facebook but it knows that it
isn't an actual user but an automated program and isn't working. Anybody
know how I might be able to get authenticated?
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!");
}
No comments:
Post a Comment