Facebook Java Api(ENG)

Facebook Java Api Example


This article explain the facebook java api through an example.
First you need a facebook account, and you have to enable "Developer" application.

Then you must configure you account and make a new application configuration in order to obtain 
"api key" and "secret key".
This can be accomplished by reading http://developers.facebook.com/get_started.php

The Server

You need a java web server (tomcat, glassfish, jboss etc.) available by the web.
Localhost server isn't ok to facebook integration purpose.

Facebook Java Api

If you want to interact with facebook platform a client library can be very useful.
Client library are available in different languages:http://wiki.developers.facebook.com/index.php/Client_Libraries

There isn't a officiale Java api but you can choose alternative unofficial ones:

I prefer the last one.
So go to http://code.google.com/p/facebook-java-api/ and download facebook-java-api-2.0.4.bin.zip (or later).
When you download it, extract the jar into a directory and get it available in you facebook example application classpath.

Facebook server make available user data, photos, groups infos etc by rest api:http://wiki.developers.facebook.com/index.php/API

The Facebook Client Project

Make a new Web project, and make a new empty servlet.
The servlet url-pattern configured in web.xml must be the same indicated in facebook application configuration.

The Source Code

public class index extends HttpServlet

    //facebook give it!
    String apiKey = "your api key";
    String secretKey = "your secret key";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        PrintWriter out = response.getWriter();
            out.println("<h2>User information</h2>");

            //facebook login mechanism give you by http parameter the session key
            //needed for client api request.
            String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

            //initialize a facebook xml client (you can choose different client version: xml, jaxb or json)
            //the init is done by apiKey, secretKey and session key previosly requested
            FacebookXmlRestClient client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);

            //This code line obtain the user logged id
            Long uid = client.users_getLoggedInUser();

            //print user info.
            out.println(printUserInfo(uid, client, sessionKey));


private String printUserInfo(Long uid, FacebookXmlRestClient client, String sessionKey) throws FacebookException
        StringBuffer ret = new StringBuffer();
        //init array parameter
        ArrayList<Long> uids = new ArrayList<Long>(1);
        //init field parameter - we choose all profile infos.
        List<ProfileField> fields = Arrays.asList(ProfileField.values());
        //init the client in order to make the xml request
        client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);
        //get the xml document containing the infos
        Document userInfoDoc = client.users_getInfo(uids, fields);
        //for each info append it to returned string buffer
        for (ProfileField pfield : fields)
            ret.append(pfield.fieldName()).append(" <b>").append(userInfoDoc.getElementsByTagName(pfield.fieldName()).            item(0).getTextContent()).append("</b>");
        return ret.toString();

In this simple manner you can print all logged facebook user info into facebook application. In order to make a cleary client authentication by using java servlet filter you can read this:

TrovaTv Samsung and facebook



Anu said...

Hi, Thanks for the information. I ran into your blog, while searching examples related to Data Mining with Facebook Java api. My current project involve data extraction from facebook api and load them into a data model. Is it possible that you could provide some guidance such as where should I start from, and any helpful tutorial for such task.


Giuseppe Morreale said...

This post is already a little starting point for facebook data extraction.

For the next steps you have to understand what type of data mining do.
You have to choose data model, and determine what type of study conduct.
Is a too bigger theme and it involve many technologies and possibilities. Divide your objective in subproblem and analize it step by step.

Take care about facebook agreement about data manipulation!!

Good Luck!

Anu said...

Thanks alot for the reply, I am a grad student and this is a research project Yeah so far we have created the data model with five tables. I have identified that Groups node have more data exposed than user node.

Thanks, Anu

Anu said...

Hi, I tried to run your code in eclipse to understand and see the process. But It didn't work. I created it as a Servlet and add both API_KEY and SECRET_KEY into my web.xml. I used Tomcat(localhost) within eclipse to launch. Also I didn't understand what you meant by " You need a java web server (tomcat, glassfish, jboss etc.) available by the web.
Localhost server isn't ok to facebook integration purpose."
Is this mean that I can't use local host.

Giuseppe Morreale said...

Yes it's correct!
Facebook need to comunicate with a server in the web.
localost isn't in the web!

Anu said...

Is this mean I have cant execute this on eclipse? Is it possible for you to give some instructions on running your code. Coz I am bit confuse, I was following similar examples which were available online. But none of them seams to work, even an example that I found in screen cast.

Giuseppe Morreale said...

The problem isn't eclipse, netbeans or other ones.. The problem is localhost.
localhost isn't reachable from facebook server, so it can't works.
You need a server reachable from facebook server(from the web).

For example, if you make a website in localhost, can you say to your friend to visit the website from their home? You can't. It is the same problem.

Dinesh786 said...

hello i worked on this exapme but i got this error com.google.code.facebookapi.FacebookException: Session key invalid or no longer valid

please tell me how to get session id or jar will manage it will provide

Giuseppe Morreale said...

you have to configure you account and make a new application configuration in order to obtain
"api key" and "secret key".
This can be accomplished by reading http://developers.facebook.com/get_started.php

Dinesh786 said...

i got api and secret key by application now i need to deploy my application on local server i taen your code and updated and deployed but i am getting errorcom.google.code.facebookapi.FacebookException: Session key invalid or no longer valid

Giuseppe Morreale said...

What do you mean with localserver?
Is it localhost? If it is you need a server available by ip or domain remotely in the web.

Kishore Gara said...

I got the following error, when I deployed it with the same steps in face book. Is there any way to fix it?

Face book url: http://apps.facebook.com/staticwivo/Login


java.lang.RuntimeException: java.net.ConnectException: Connection timed out
at com.google.code.facebookapi.ExtensibleClient.runtimeException(ExtensibleClient.java:2017)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:538)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:458)
at com.google.code.facebookapi.ExtensibleClient.users_getLoggedInUser(ExtensibleClient.java:722)
at com.wivo3.action.Login.processRequest(Unknown Source)
at com.wivo3.action.Login.doGet(Unknown Source)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:516)
at java.net.Socket.connect(Socket.java:466)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
at sun.net.www.http.HttpClient.New(HttpClient.java:287)
at sun.net.www.http.HttpClient.New(HttpClient.java:299)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:795)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:747)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:672)
at com.google.code.facebookapi.ExtensibleClient.postRequest(ExtensibleClient.java:562)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:534)
... 20 more

Giuseppe Morreale said...

It seems a connection problem like a firewall lock.

devinka said...

Thanks for the information Giuseppe.



Giuseppe Morreale said...

Thanks! ;)

devinka said...


can you please update your blog adding how to publish on wall in face book using Java api. : D


Giuseppe Morreale said...

Hi, Sorry but now I'm too busy for writing in the blog.
I'll be happy to satisfy your request later.

TheUnical Technologies said...

Nice post.
Here is another link which describes all steps to publish on facebook wall

Rishika said...

I m facing a prob, can you please help me .
I have created a site , I want to get the location of the people who liked my site through facebook using Facebook java API.

hary's said...

hi, thanks for the information and is their any chance to get facebook like counts and user info who clicked flike button in my site. if it is possible please let me know how to get user info and flike counts details.

marshall said...

Wow! What a load of information! Thank you so much!

facebook applications developers

mohit taparia said...


Does this still work??