How to obtain an Access Token (user and page) from Facebook for publishing post in Java API

1. Go to “developers.facebook.com” and log in with your identity

2. Go to “My Apps” and create an application

3. Go to “Tools & Support” and check on “Access Token Tool”

4. Go to “Tools & Support” and check on “Graph API Explore”

Facebook_Access_Token_2

5. If you want to publish a message with picture, you should make sure “publish_actions” is included in “Scopes.”

Facebook_Access_Token

How to get your Page AccessToken and PageID

1. Go to https://developers.facebook.com/tools/explorer
2. At the GET request form, down there, fill in me/accounts
3. You’ll get a Javascript representation of your basic user data. Find the page you want.
4. Note the access_token and id fields, we’re going to use them in the code below.

 

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookException;
import com.restfb.types.FacebookType;
import com.restfb.types.Page;
import com.restfb.types.User;


public class FacebookConnector {

    /* Variables */
    private final String pageAccessToken = "GET_THIS_FROM_THE_INSTRUCTIONS_ABOVE";
    private final String pageID = "THIS_TOO";
    private FacebookClient fbClient;
    private User myuser = null;    //Store references to your user and page
    private Page mypage = null;    //for later use. In this answer's context, these
                                   //references are useless.
    private int counter = 0;

    public FacebookConnector() {
        try {

            fbClient = new DefaultFacebookClient(pageAccessToken);
            myuser = fbClient.fetchObject("me", User.class);
            mypage = fbClient.fetchObject(pageID, Page.class);
            counter = 0;
        } catch (FacebookException ex) {     //So that you can see what went wrong
            ex.printStackTrace(System.err);  //in case you did anything incorrectly
        }
    }

    public void makeTestPost() {
        fbClient.publish(pageID + "/feed", FacebookType.class, Parameter.with("message", Integer.toString(counter) + ": Hello, facebook World!"));
        counter++;
    }

}
Advertisements