ZOFTINO.COM android and web dev tutorials

Publishing Messages & Pictures to Facebook Page Using RestFB

Facebook provides API to get data from Facebook and publish data to Facebook. If you own a business and want to interact with customers on Facebook, posting messages using tools , which rely on Facebook API, saves time and resources. Creating tools to read data from and post data to Facebook is very easy. I am going to show how to develop a tool using RestFB framework to publish messages and pictures to facebook page.

It is very important to make sure that your tools post quality messages which are useful to your target audience. And also there are rate limits on API which need to be followed. For rate limits visit Rate Limiting on the Graph API .

We are going to use RestFB client framework written in Java to access Facebook Graph API. You can download RestFB jar under the terms of MIT license.

To use Facebook Graph API, you need access token and your facebook app secret. You can register and configure your facebook app here.

Below code can be used to publish just message and message with image to your Facebook page, don’t forget to include restfb jar in classpath.


	public boolean postMessage(String fbmessage, String imgurl) throws Exception{

		String pageAccessToken = "fbaccesstoken";
		String fbappsec = "yourfbappsecret";
		String pageID = "youfbpageid";

		FacebookClient fbClient = new DefaultFacebookClient(pageAccessToken, fbappsec, Version.VERSION_2_3);

		if(imgurl != null){
			File imfile = new File(imgurl);
			if(!imfile.exists()){
				return false;
			}
			InputStream targetStream = new FileInputStream(imfile);

			byte[] photodata = IOUtils.toByteArray(targetStream); 
			String photoNme = cu.getFileNameFromFullPath(imgurl);
			FacebookType photo = fbClient.publish(pageID + "/photos" , FacebookType.class,
					BinaryAttachment.with(photoNme, photodata), Parameter.with("privacy", "{'value': 'SELF'}"));
			Link photoLink = fbClient.fetchObject(photo.getId(), Link.class);
			FacebookType post =  fbClient.publish(pageID + "/feed", FacebookType.class,
					Parameter.with("message", fbmessage),Parameter.with("type", "photo"),
					Parameter.with("link", photoLink.getLink()));
		}else{
			FacebookType post =  fbClient.publish(pageID + "/feed", FacebookType.class,
					Parameter.with("message", fbmessage));				
		}


		return true;
	}