I managed to work it out. Below is a simple class I made to make posts in one of my Pages as the page itself!
Pre-code instructions: Get your Page AccessToken and PageID
- Go to https://developers.facebook.com/tools/explorer
- At the GET request form, down there, fill in me/accounts
- You'll get a Javascript representation of your basic user data. Find the page you want.
- Note the
access_token
andid
fields, we're going to use them in the code below.
That's it. Now,
Onto the program code!
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;
/**
*
* @author dsfounis
*/
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++;
}
}
Result:
After calling makeTestPost()
a few times:
Some notes:
I'm pretty sure the pageID could also take a String
of your page name, which you can see at the link of your page, when visiting it. http://facebook.com/mypagename
, so you could substitute the pageID number with "mypagename"
.
Another thing: The publish()
method used above will fail if the previous post is the exact same as the one you're trying to post now, probably an anti-spam mesaure. This is why I implemented the counter
, so I could test it properly. Apart from that restriction, the makeTestPost()
passed the Monkey Test.
Finally, my practices may be unoptimal or simplistic, but like yourself I spent hours getting lost in incomplete documentation and information about RestFB.