Saturday, February 26, 2011

Facebook API from Java code

I just got started with Facebook (graph)  API and fetch data from native Java programs for my project requirements .First of all I created an sample app at and got the necessary details about the app at the summery.

Once I registered the app it was time to give permission from my user account to the app so that it can access ( so the API ) data from my account.

MY_URL was any random url as the landing page after I log in was immaterial in this case as I was going to use the APIs from the java code.

I addded offline_access so that it does not time out , I can use the access token generated forever.
Now after I allowed access it landed on a page similar to the following

To get the access_token I invoked following

once the access token appeared in the response I invoked various graph APIs to test if data is coming in JSON format<Access_token_obtained_from_last_step>
gives me all my wall posts<POST_ID>?access_token=<Access_token_obtained_from_last_step>
gives me all the comments for a given post id of mine

I also used json-simple to parse and decode the JSON returned by the above Facebook APIs.







import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.JSONValue;

public class FindComments {

* @param args

* @throws IOException


public static void main(String[] args) throws IOException {
String commentID = "<COMMEN_ID>";

String accessToken = "<ACCESS_TOKEN>";
// TODO Auto-generated method stub

URL yahoo = new URL(


URLConnection yc = yahoo.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(yc


String inputLine;

String s = "";

while ((inputLine = in.readLine()) != null)

// System.out.println(inputLine);

s = s + inputLine + "n";

// System.out.println(s);
Object obj = JSONValue.parse(s);

// JSONArray array=(JSONArray)obj;

// System.out.println(obj);

// System.out.println(array.get(1));

JSONObject obj2 = (JSONObject) obj;
JSONObject comments = (JSONObject) obj2.get("comments");

JSONArray commentsArray = (JSONArray) comments.get("data");

// System.out.println(commentsArray.size());

// System.out.println(obj2.get("comments"));

for (int i = 0; i &lt; commentsArray.size(); i++) {

JSONObject commentobj = (JSONObject) commentsArray.get(i);

// System.out.println(commentobj);

String commentText = (String) commentobj.get("message");




The above code prints the comments given on the Hard coded post ID