RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


How to Integrate Facebook and Twitter with Java Applications

Exposure on social media sites such as Facebook, Twitter and LinkedIn has a tremendous impact on business, effecting marketing, networking, analytics and more. Social media is a natural resource for collecting user feedback, comments, suggestions, etc., making the integration of social media with applications increasingly important. This article will discuss the integration of Facebook and Twitter with a Java application.


In the modern era, web sites have become an integral part of any business—big and small. The presence of a business on the web is not necessarily enough to reach a global mass audience. Social media plays a significant role in reaching a wider audience as it has a cascading and concurrent effect. Social networking and media sites themselves are also interested in integration and communication with other web sites, exposing their APIs and allowing web sites to communicate and integrate with them. Facebook provides convenient APIs (known as Graph API) for this purpose. The Graph API is very powerful and flexible. It exposes all necessary features (known as interfaces) required for integration.

Facebook Application Model

Before going into the actual implementation, let’s understand the Facebook application model. Facebook opens its platform to developers using REST web services. As a developer, you are free to use the APIs of your choice to integrate Facebook features in your application. You are also free to use the technology of your choice. Facebook uses a proxy server model as a main integration point. The Facebook proxy server follows the following steps:

  • The web application will reside in your web/application server and you need to register the base URL in a Facebook account.
  • When the application is visited in Facebook, it will call the registered URL on the application server.
  • The application will call necessary Facebook APIs to get the relevant information.
  • Your application uses its own database data and Facebook data and render it
  • After this Facebook returns your application's output to the user

How to Get Facebook Libraries

Before we integrate Facebook with your Java application we need some third party libraries. These third party libraries will help you with integration and communication with Facebook (actually accessing Facebook application installed in their server). Different independent groups of Java and open source developers have made efficient Facebook libraries for integration purpose.

You can check http://code.google.com/p/Facebook-java-api to get more details about the APIs and Jars. These third party libraries are compatible with Java SE 5 and above.

Download the following JAR files

If you are using a Java application server on top of Java SE 5, then you should download the following JAR files:

The three JARs above are not required if you are using Java SE 6 or later.

After downloading these JARs, you need to incorporate them in your web or stand alone application. These JARs are made to provide API access to the client application for different purpose.

The following example will show the integration part:

Listing 1: Sample Java code for Facebook integration

package com.home.social;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import Facebook4j.Facebook;
import Facebook4j.FacebookException;
import Facebook4j.FacebookFactory;
import Facebook4j.Post;
import Facebook4j.ResponseList;
import Facebook4j.conf.Configuration;
import Facebook4j.conf.ConfigurationBuilder;

public class FacebookIntegration {
	public static void main(String[] args) throws FacebookException {
		// Create conf builder and set authorization and access keys
		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
				.setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic");

		// Create configuration and get Facebook instance
		Configuration configuration = configurationBuilder.build();
		FacebookFactory ff = new FacebookFactory(configuration);
		Facebook Facebook = ff.getInstance();

		try {
			// Set search string and get results
			String searchPost = "MACDonaldsIndia";
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
			String fileName = "D:\\FacebookConfigFolder\\File\\" + searchPost
					+ "_" + simpleDateFormat.format(date) + ".txt";
			String results = getFacebookPostes(Facebook, searchPost);
			File file = new File(fileName);
			if (!file.exists()) {
				FileWriter fw = new FileWriter(file.getAbsoluteFile());
				BufferedWriter bw = new BufferedWriter(fw);
		} catch (IOException e) {

	// This method is used to get Facebook posts based on the search string set
	// above
	public static String getFacebookPostes(Facebook Facebook, String searchPost)
			throws FacebookException {
		String searchResult = "Item : " + searchPost + "\n";
		StringBuffer searchMessage = new StringBuffer();
		ResponseList<Post> results = Facebook.getPosts(searchPost);
		for (Post post : results) {
			searchMessage.append(post.getMessage() + "\n");
			for (int j = 0; j < post.getComments().size(); j++) {
						+ ", ");
						+ ", ");
						+ ", ");
						+ "\n");
		String feedString = getFacebookFeed(Facebook, searchPost);
		searchResult = searchResult + searchMessage.toString();
		searchResult = searchResult + feedString;
		return searchResult;

	// This method is used to get Facebook feeds based on the search string set
	// above
	public static String getFacebookFeed(Facebook Facebook, String searchPost)
			throws FacebookException {
		String searchResult = "";
		StringBuffer searchMessage = new StringBuffer();
		ResponseList<Post> results = Facebook.getFeed(searchPost);
		for (Post post : results) {
			searchMessage.append(post.getFrom().getName() + ", ");
			searchMessage.append(post.getMessage() + ", ");
			searchMessage.append(post.getCreatedTime() + "\n");
		searchResult = searchResult + searchMessage.toString();
		return searchResult;

	// This method is used to create JSON object from data string
	public static String stringToJson(String data) {
		JsonConfig cfg = new JsonConfig();
		try {
			JSONObject jsonObject = JSONObject.fromObject(data, cfg);
			System.out.println("JSON = " + jsonObject.toString());
		} catch (Exception e) {
		return "JSON Created";

Integration with Twitter

In order to integrate your application with Twitter, we need to use the library - Twitter4j. This is a well documented library that helps any Java developer to integrate his/her application with Twitter. As a developer you need to follow certain steps:

  • Send a request to Twitter asking for a token. This request should carry both a consumer key and a secret key.
  • Store the response received from Twitter.
  • Once the response is received, the authentication URL is extracted from the response.
  • The user then needs to be redirected to the authentication URL, so that he can sign in.
  • User signs in and gets a Personal Identification Number or PIN.
  • User then enters PIN in the application.
  • Once the PIN is entered the application should ask Twitter for a security token, providing consumer parameters as above as well as the previously stored request token and the PIN.
  • Once the token is received, every request going to Twitter should have this token along with the PIN

Listing 2: Sample Java code for Twitter integration

package com.home.social;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.List;

import Twitter4j.Query;
import Twitter4j.QueryResult;
import Twitter4j.Status;
import Twitter4j.Twitter;
import Twitter4j.TwitterFactory;
import Twitter4j.conf.ConfigurationBuilder;

public class TwitterIntegration {
	public static void main(String[] args) throws Exception{
		// Create configuration builder and set key, token etc
		ConfigurationBuilder cb = new ConfigurationBuilder();

		// Create Twitter instance
		Twitter Twitter = new TwitterFactory(cb.build()).getInstance();

		// Create file writer and buffer writer
        FileWriter fstream = new FileWriter("Twitterstream.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);

		// Create Query object and set search string
		Query query = new Query("");

		// Get query result
		QueryResult qr = Twitter.search(query);

		// Get tweets and write in the file
			List<Status> tweets = qr.getTweets();

			for (Status t: tweets){
				System.out.println(t.getId() + " - " + t.getCreatedAt() + ": " + t.getText());

		}catch(Exception e) {}


There are many social networking web sites available--out of these Facebook and Twitter are the most commonly used. Java provides libraries to easily integrate your applications with these web sites. Social media integration is a new dimension in the developer's world and you should explore it as much as possible.


About the Author

Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies. You can find more of his work at www.techalpine.com and you can email him here.

Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date