Posting to all Facebook pages using Facebook APIs in Java

If you are admin of multiple Facebook pages, posting same stuff to all pages might be a bit tedious. Let’s write a simple Java program which can post links, photos or messages to all the Facebook pages you are admin of. We will be using restFb java client for invoking Facebook’a APIs

1. Get facebook access token
Doing facebook oauth login

2. Get all pages in which current user is admin

final List<Page> con = facebookClient.fetchConnection("me/accounts",
				Page.class).getData();

3. Get page access token

String token = page.getAccessToken();

4. Create new facebook client based on Page access token

FacebookClient innerclient = new DefaultFacebookClient(token);

5. Get Page ID

String id = page.getId();

6. Now publish the message to the Page’s feed

innerclient.publish(id + "/feed", FacebookType.class,
							Parameter.with("message", status));

7. If you are posting link, use this code

innerclient.publish(id + "/feed",FacebookType.class,
	Parameter.with("message", status),
	Parameter.with("link", link));

8. If you have to publish an image, first lets find the ID of the timeline album

JsonArray data = facebookClient.fetchObject(id + "/albums",
						JsonObject.class).getJsonArray("data");
				String wallid = "";
				for (int i = 0; i < data.length(); i++) {
					JsonObject obj = (JsonObject) data.get(i);
					if (obj.getString("name").equalsIgnoreCase("Wall Photos")
							|| obj.getString("name").equalsIgnoreCase(
									"Timeline Photos")) {
						wallid = obj.getString("id");
						break;
					}
				}

9. Now you can upload the photo to timeline album. Here fis is the file inputstream which contains the image to be published

innerclient.publish(id + "/photos",
							com.restfb.types.Photo.class,
							BinaryAttachment.with(id + "final.jpg", fis),
							Parameter.with("message", status));

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *