Wednesday, May 5, 2010

A tiny Java connector for Facebook

This article explains my spare time initiative, a small piece of Java connector for Facebook API. Though I completed this piece of code back in early 2008, I didn't get enough time to structure this write up.... Anyway..., it demonstrates a set of key concepts e.g. authentication, signature code and session key generation to access REST architecture based Facebook API.

Rather than providing a complete API solution, I believe it will help to understand specific concepts like the connection setup process that runs behind any 3rd party Facebook Connection API. So, let’s start....


Pre-Requisites

Please follow these steps before you start the implementation-

  • Register with Facebook
  • Register your application with Facebook (Registering an application will give you API Key and Secret Key)
  • Go To http://www.facebook.com/developers/ and Register an Application (You have to just specify any name for your application e.g. “Test”)
  • Collect API Key and Secret. Both API Key and Secret consists of 32 alphanumeric.


Facebook API
Facebook provides a REST based API for developers to create applications which can be integrated with Facebook. Each REST URL signifies a different set of information object.

There is a little bit difference in the way a Web Application access this API from Desktop applications. I will not elaborate this as you will get sufficient information on Facebook Developer's Section.

The Java connector consists of 2 core modules- HTTP Handler and Signature Generator.

HTTP Handler

It sends POST HTTP requests to http://api.facebook.com/restserver.php for accessing Facebook API methods. Following code snippet sends and receives HTTP POST request/response-


URL FB_URL = new URL(“http://api.facebook.com/restserver.php”);

HttpURLConnection conn = (HttpURLConnection)FB_URL.openConnection();

conn.setRequestMethod("POST");

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

conn.connect();


//Send Request Parameters

System.out.println ("Sending Request Parameters...");

OutputStream out = conn.getOutputStream();

out.write(reqParms.getBytes());

out.flush();


System.out.println ("Response Code="+conn.getResponseCode());

System.out.println ("Get Response...");

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;

StringBuffer outputData = new StringBuffer();

while ((line = rd.readLine()) != null) {

// Process line...

outputData.append(line);

System.out.println(line);

}


reqParms
is a string concatenation of HTTP POST request parameters e.g. api_key=API_KEY&v=1.0



Signature Generator

Following steps depicts implementation of the signature code generation algorithm (explained here)-


Step1- Define a String Array to hold API parameter-value pairs-

Define a String Array to hold all the HTTP parameter values to

be passed along with the REST URL-

http://api.facebook.com/restserver.php?parm1=value1&....

apiReqParms: is the String array of HTTP parameter values e.g.


String apiReqParms[] = {"method=auth.getSession","api_key=API_KEY"};



Step2- Sort the String Array

// Sort the apiReqParms Array Alphabetically

Arrays.sort(apiReqParms, String.CASE_INSENSITIVE_ORDER);



Step3- Concatenate all parameter-value pairs

// Concatenate all the parameter-value pairs and the API Secrete string

String reqParmsStr = "";

// Concate

for (int i = 0; i <>

reqParmsStr += apiReqParms[i];

}

reqParmsStr += SECRET;



Step4- Generate MD5

// Generate the MD5 Hash of the string generated in Step3

java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");

md.update(reqParmsStr.getBytes());

byte keyB[] = md.digest();



Step5- Generate Signature

/*

* Generate Hexadecimal Code of the 16 byte hash obtained in Step4.

* The generated Hex code is the signature to be used for connectivity.

*/

String signature = getHexCode(keyB);


public String getHexCode(byte byteA[]){

byte dig = 0;

//Capital letters doesn't work with Facebook API

char hexCode[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

String hexVal = "";

byte msn,

lsn;

for(int i=0; i

dig = byteA[i];

msn = (byte)((dig >> 4)&0x0F);//Most Significant Nibble

lsn = (byte)(dig&0x0F);//Least Significant Nibble

hexVal = hexVal + hexCode[msn] + hexCode[lsn];

}

return hexVal;

}



Once you cover all the above 5 steps you will get a workable 16 byte MD5 Hash (in Hexadecimal) which can be used for API access.


Session Key Generation

There is a concept of Infinite Session in Facebook which allows applications to use and stay online forever until corresponding user explicitly logged out. By default Facebook gives One-Time Session Key.

Following steps depectics the process to generate infinite session key-

Step1: Access following URL with your API_KEY using the browser-

http://www.facebook.com/code_gen.php?v=1.0&api_key=API_KEY


Step2: Note the Authentication Token returned in Step1 (consistes of 6 characters).


Step3: Call auth.getsession function of REST API by passing Auth_Token (obtained from Step2) as input parameter to generate the Session Key (consists of 32 characters).


Step4: Use the Session Key obtained from Step3 in your application.


Once you have the Session Key, your application will be able to connect to Facebook server. Now as you are able to successfully connect to Facebook server, you can use the HTTP Handler module to access different Facebook API methods and need to develop an XML parser to extract output of these method invocation.


So you are all set to develope the next killing Facebook App...All the best :-)

I hope this small piece of work will help people who wants to explore the anatomy of Facebook API connection setup. Any feedback and comments are greatly appreciated....


Reference

No comments:

Post a Comment