Logging in with Facebook Java API

Facebook is no longer maintaining its Java api.

Luckily the Java community is large enough to support an alternate project called, appropriately, facebook-java-api. This is hosted on google code and is well done.

My only issue – how to get going when you’re at square zero with the Facebook API.

Prep work

  1. Download facebook-java-api. Make sure this jar and all of the required jars are in your project’s classpath.
  2. Register a Facebook Application. You’ll need a Facebook account to do this. This creates your API key and Secret for authenticating Facebook users with your application.

About Facebook Application Authentication

Authenticating with the Facebook client API is pretty straight forward.

  1. Construct your client with your API key and Secret
  2. Obtain an auth token
  3. Authenticate a user with the auth token

Step 3 requires you to redirect the user to Facebook hosted URL. This is straightforward if you are building a web application. If you are developing a desktop application, you’ll need to open a browser and have them enter the information there.

Your users will be greeted with something like this -


Replace the red strike-throughs with your application name

After they enter their login information, they will have created a session that is associated with your auth token that you obtained.

The Code

The following code sample demonstrates authenticating your application, logging a user into your application and finally fetching the user’s friend list. You’ll need to add your package and import statements as necessary.
 

/**
 * FacebookClient
 * 
 * @author Mitch Coopet, Code 42 Software, Inc.
 */

public class FacebookClient {    
  public static String API_KEY = “YOUR API KEY”;
  public static String SECRET = “YOUR SECRET”;
  public static void main(String args[]) {
    // Create the client instance
    FacebookRestClient client =       new FacebookRestClient(API_KEY, SECRET);
    client.setIsDesktop(true); // is this a desktop app

    try {
      String token = client.auth_createToken();
      // Build the authentication URL for the user to fill out
      String url = http://www.facebook.com/login.php?api_key=” 
                + API_KEY + “&v=1.0″ 
                + “&auth_token=” + token;
      // Open an external browser to login to your application
      Runtime.getRuntime().exec(“open “ + url); // OS X only!
      // Wait until the login process is completed
      System.out.println(“Use browser to login then press return”);
      System.in.read();

      // fetch session key
      String session = client.auth_getSession(token,true ); 
// obtain temp secret
String tempSecret = client.getSessionSecret();
// new facebook client object
client = new FacebookJaxbRestClient(API_KEY, tempSecret, sessionKey);

      System.out.println(“Session key is “ + session);

      // keep track of the logged in user id
      Long userId = client.users_getLoggedInUser(); 
      System.out.println(“Fetching friends for user “ + userId);

      // Get friends list
      client.friends_get();
      FriendsGetResponse response = (FriendsGetResponse) client.getResponsePOJO();
      List<Long> friends = response.getUid();

      // Go fetch the information for the user list of user ids
client.users_getInfo(friends, EnumSet.of(ProfileField.NAME));

UsersGetInfoResponse userResponse = (UsersGetInfoResponse) client.getRepsonsePOJO();
      // Print out the user information
      List<User> users = userResponse.getUser();
      for (User user : users) {
        System.out.println(user.getName());
      }
    } catch (FacebookException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

About these ads

About mcoopet

Co-founder of Code 42 Software, Inc. The guy behind the scenes at work and at home
This entry was posted in Java and tagged , . Bookmark the permalink.

18 Responses to Logging in with Facebook Java API

  1. tabanyi says:

    The auth_getSession throws a NullPointer, but if i try without setIsDesktop(true) then it works.

  2. al says:

    Hey, just got started programming facebook apps using java, and your site was a tremendous help. Thanks for posting it.

  3. sunita says:

    hey thanks .. tabanyi ur comment really helped me alot .. :)

  4. peppe says:

    I write an example using facebook java api
    It use FacebookXmlRestClient in order to make client request and print
    all user infos
    http://programmaremobile.blogspot.com/2009/01/facebook-java-apieng.html

  5. vee says:

    could you give me an example on how to ask the permission to the user to get his offline access. after logging in???

    Well, in other words, how do I redirect the user to another url after logging in?

    thanks before

  6. monkeyvu says:

    Thanks for your article. It’s cool.

    I have a question. I’m going to update the user’s status so I grant the permission for my app like below:

    String url = “http://www.facebook.com/login.php?api_key=” + “657dd4a7fb94100330947f1″ + “&v=1.0″ + “&auth_token=” + token + “&ext_perm=status_update”;

    But I still don’t have the update_status permission.

    if ( client.users_hasAppPermission( Permission.STATUS_UPDATE ) ) { …

    Do you know the reason?

    Thanks,

  7. Agus Suhanto says:

    I’m a little bit frightened to begin work with facebook with java, but I have to. I think your explanation help me much here… I should try now

  8. Agus Suhanto says:

    After some hours of ‘understanding’ session, now I’ve been able to connect to facebook using java api.

    This API has been changed so much now, especially when dealing with desktop app. If application is set to ‘Desktop’ mode, we are require to use temp secret, not original secret.

    Here is the code after login screen authentication:

    // obtain session
    String sessionKey = client.auth_getSession(token, true);
    // obtain temp secret
    String tempSecret = client.getSessionSecret();
    // new facebook client object
    client = new FacebookJaxbRestClient(API_KEY, tempSecret, sessionKey);

  9. Agus Suhanto says:

    @monkeyvu,
    it’s not enough only to include req_perms=status_update in URL.

    After login, we have to ‘prompt’ the user for one time allowing our application to get the status_update permission.

    Here is URL to do it:
    String permURL = “http://www.facebook.com/connect/prompt_permissions.php?api_key=” + API_KEY + “&v=1.0″ + “&ext_perm=status_update”;

  10. adit says:

    Hi mcoopet, thanks for your tutorial. it works as i expected. do you know how to get authentication without opening any browser?

    • mcoopet says:

      Adit –

      Technical answer – yes, you can do this without opening a browser. You can use java to ‘screenscrape’ the login interaction by using a library like HTMLUnit:

      http://htmlunit.sourceforge.net/

      That said, I don’t recommend this method as it doesn’t abide by Facebook standards and may even be against its terms of service.

  11. Pingback: Playing with FACEBOOK Java API – Just another WordPress instance

  12. Pingback: Social Media Development » Authentication mit Facebook Connect

  13. rachasatish says:

    Good Here is the detailed post
    http://blog.theunical.com/facebook-integration/facebook-java-api-example-to-publish-on-wall/
    Php libraries are more easier than Java libraries for Facebook.

  14. Youssef says:

    Please i’m getting started with java apis , well i’m working on Netbeans , and i don’t really know the statements i gotta import besides the link i found below , if there is any help it will be welcome wide open thanx !

    • Griffin says:

      Just do the following steps:
      1- Right click on your project
      2- Choose libraries
      3- Add jar/folder
      4- Select the location of the jar

      that’s it!

  15. mcoopet says:

    This article is extremely old (2008) and is no longer being maintained.

    Keep that in mind when referencing :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s