Pages

Sunday, December 19, 2010

Experimenting with Facebook API

I've got to be honest.
The Java API for Facebook was horribly documented and is out-of-sync with the current version of their library. The following code works for JAR version 1.7.*.
My goal was simple - login to facebook and download names of a person's friends.


public static void main(String[] args) {
System.out.println("FacebookProfile");
IFacebookRestClient client = new FacebookXmlRestClient(API_KEY, SECRET_KEY);
try {
String token = client.auth_createToken();
String url = "http://www.facebook.com/login.php?api_key=" + API_KEY
+ "&v=1.0" + "&auth_token=" + token;
System.out.println(url);
Runtime.getRuntime().exec("explorer \"" + url + "\"");

System.out.println("Use browser to login then press return");
System.in.read();

String session = client.auth_getSession(token);
System.out.println("Session key is " + session);

client.friends_get();
FriendsGetResponse friendsResp = (FriendsGetResponse)client.getResponsePOJO();

List friends = friendsResp.getUid();
System.out.println("ID List of Your Friends");
System.out.println(friends);


client.users_getInfo(friends, EnumSet.of(ProfileField.NAME));

UsersGetInfoResponse userResponse =
(UsersGetInfoResponse) client.getResponsePOJO();

List users = userResponse.getUser();
for (User user : users) {
System.out.println(""+user.getName()+"");
}

} catch (FacebookException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Reactions: