Bulk Emailing

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Tuesday, 4 May 2010

A tiny Java connector for Facebook

Posted on 18:31 by Unknown

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

  • Signature Generation and Authentication Algorithm :- http://wiki.developers.facebook.com/index.php/How_Facebook_Authenticates_Your_Application
  • Facebook API Doc :- http://wiki.developers.facebook.com/index.php/API

Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Weekend at Yeouido (Han River Cruise)
    Yeouido is one of the Han River Cruise boarding points. It has a wonderful river side park (Yeouido P...
  • CityWeather
    Update: Release 1.1 has been uploaded. It will now provide weekly forecast of your selected cities. Download   CityWeather is an Android...
  • Few Multi-Threading Implementations
    Sequential Producer & Consumer In my first example, I will demonstrate an implementation to solve ...
  • Accessing Yahoo Finance API
    Since last few days I was wondering the right set of Web Service to read Country wise Stock Exchange index information . I found a bunch of ...
  • Regular Expression in JavaScript
    I was struggling to get familiar with JavaScript's Regular expression handling and thought my learning might help others. Here I'll...
  • Alphanumeric Random Number
    Sometime basic things becomes tricky :-) Was trying to find out ways to generate some alphanumeric random number whose size (i.e. number of ...
  • Binary Search Tree in Java
    This post is a part of my continuous effort to just implement few of the important data structures in ...
  • QuickSort in Java
    This post is a part of my continuous effort to just implement few of the important data structures in Java. Please find my previous post on ...
  • InDroid- Access to Android's Hidden API
    I have started one project " InDroid " to expose and share Hidden and Internal methods and variables of Android platform which are...
  • Image Geo Tagging for Android
    " onMap " is an Image Geo Tagging application, which can read EXIF header of images stored in your Android device and Map them ov...

Blog Archive

  • ►  2013 (6)
    • ►  September (2)
    • ►  May (1)
    • ►  April (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (4)
    • ►  July (2)
    • ►  March (1)
    • ►  January (1)
  • ►  2011 (11)
    • ►  November (1)
    • ►  October (2)
    • ►  August (1)
    • ►  June (1)
    • ►  April (2)
    • ►  March (3)
    • ►  January (1)
  • ▼  2010 (27)
    • ►  December (2)
    • ►  November (3)
    • ►  September (2)
    • ►  August (4)
    • ►  July (4)
    • ►  June (7)
    • ▼  May (5)
      • Few Simple Steps to Setup TWiki
      • Android Custom TextView
      • My Day with Eclipse MAT and Dominator Tree
      • An effort to find out Angling spots in Delhi & NCR
      • A tiny Java connector for Facebook
Powered by Blogger.

About Me

Unknown
View my complete profile