pagetop
Javablog
by Java coders, for Java coders RSS

Tips for writing FaceBook applications in Java

July 25th, 2007 by Daniel

So you want to write a FaceBook application using Java? You’ve added the Developer application to your FaceBook account and downloaded the Java client library. And now you’re kind of stuck. Where are the tutorials, examples and proper documentation? Frustration turns to anger, which as we know leads to the dark side.

darth_vader.jpg
“I find the lack of good Java documentation disturbing.”

Hopefully someone will right a good Java/FaceBook tutorial soon. Perhaps we will if you’d only send us some nice chocolates — though to be honest we’re still figuring it out ourselves. Meanwhile, here are some tips to help get you started. It’s not a tutorial, but it should set you on the right track.

8 tips for building Java/FaceBook apps

  1. Use Java 5.0 or higher. That’s just general advice for your health and sanity. Because we care.

  2. Ignore the java library example
    The example that ships with the java library is for a desktop app. You probably want to write a web application, so you’ll have to change a great deal. For a start you’ll need some form of web-application server. E.g. you might use TomCat. I don’t, but that is a another story and will be told another time. FaceBook web-applications have a slightly strange usage pattern. Most of your pages will be served through FaceBook. The user will request a page from FaceBook, who will then request it’s main contents from your server. Your contents will be adapted before being sent back to the user. Mostly you don’t need to worry about this — it works nicely. But be aware that JavaScript is not allowed That means if you’re using an AJAX platform, it won’t work within FaceBook. If you need AJAX — and FaceBook’s mock-ajax won’t do — then use your FaceBook pages to direct users off of FaceBook onto normal web-pages.

  3. The settings for your application in FaceBook
    Don’t forget to fill in the settings for your application in the Facebook Developer application. You should be setting:-

    • The callback URL for your application.
    • The application name - this allows you to make pages within FaceBook (i.e. pages which are framed by the FaceBook navbar and can use FBML). Once set, urls such as http://apps.facebook.com/yourappname/yourpagename will generate a request from facebook to your server.
    • A URL for new users. This is where you get to welcome them to your application and ask them to spread it on.
  4. Using FacebookRestClient
    The most important class in the client library is FacebookRestClient. This contains a host of methods which call the FaceBook server and cover most of what you’ll want to do. Unfortunately FacebookRestClient isn’t the friendliest of classes.

    • Almost all the actions require a FacebookRestClient that was constructed with a session key. If the user is logged in, you can get the session key from the CGI variables (look for FacebookParam.SESSION_KEY.toString()). Otherwise, you need to send them to a login page. Try the following:-
      // Create a sessian-less FacebookRestClient
      FacebookRestClient client = new FacebookRestClient(YOUR<em>API</em>KEY, YOUR<em>SECRET</em>KEY);
      String token = client.auth<em>createToken();
      String loginURL = &#8220;http://www.facebook.com/login.php?v=1.0&api</em>key=&#8221;
                      +YOUR<em>API</em>KEY+&#8221;&auth_token=&#8221;+token; 
      // Now redirect the user to loginURL&#8230;
      // When they come back, they should have a session key
      The method FacebookRestClient.auth_getSession() is — as far as I can tell — unnecessary. It converts a session-less client into one with a session. I found it easier just to make a new client, pulling the session information from the CGI variables.
    • Having got a FacebookRestClient with a session key, you can now call the various FaceBook-editing methods that FacebookRestClient provides. These methods make calling FaceBook easy enough. Unfortunately the methods return unprocessed XML Documents, which isn’t terribly helpful. E.g. friends_get() returns something like this:-
      
      <document>
      <friendsgetresponse>
          <uid>1</uid>
          <uid>2</uid>
          <uid>3</uid>
      </friendsgetresponse>
      </document>
      
      You’ll probably want to wrap the methods you use with code to extract the information. E.g. to actually use friends_get(), try this:-
      Document d = client.friends_get();
      NodeList userIDNodes = d.getElementsByTagName("uid");
      int fcount = ids.getLength();
      List<Integer> friends = new ArrayList<Integer>();
      for(int i=0; i<fcount; i++) {
      Node node = userIDNodes.item(i);
      String idText = node.getTextContent();
      Integer id = Integer.valueOf(idText);
      friends.add(id);
      }
      and friends now contains the id numbers for the user’s friends.
  5. Servlets return page fragments
    When making pages within FaceBook, i.e. with urls such as http://apps.facebook.com/yourappname/yourpagename you must return an HTML/FBML fragment, and not a full HTML page.

  6. Learn FBML. This is a set of special FaceBook tags. They provides you with the easiest way to do many things (e.g. display user names and pictures).

  7. Inviting the user’s friends
    So you want to do the viral ‘invite your friends’ thing? Facebook recently changed their API (November 2007). The new improved API is based around a special form, fb:request-form. It is described here: http://wiki.developers.facebook.com/index.php/Fb:request-form. The method for this used to be FacebookRestClient.notifications_sendRequest(). This will no longer work — you’ll get an exception.

  8. The profile page
    To put content on a user’s profile page, use FacebookRestClient.profile_setFBML(). This overrides whatever default profile-page content you specified in the application settings. When you set a user’s profile FBML FaceBook will cache this content. It does not ask you for updates when the profile is viewed. This makes dynamic profile content a bit fiddlier than it would otherwise be. You’ll need to update the affected profiles with fresh calls to profile_setFBML() in response to events. Fortunately, although you need a logged in client to do anything, that client can set profile content for any of your users.

That’s all

I’m still very much a beginner regarding the FaceBook API. So if you’re an expert, please do comment below.

Best of luck in creating Web2.0 wonderfulness!


This entry was posted by by Daniel on Wednesday, July 25th, 2007 at 6:27 pm, and is filed under FaceBook, Java, Tips, Web2.0. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



61 comments on “Tips for writing FaceBook applications in Java”

Awesome, needed that badly.

More please, keep up the good work.

[...] Javablog » Tips for writing FaceBook applications in Java - Maybe one day? I’m still dubious of FaceBook applications. . . [...]

Sorry i am trying to see what would happened :) this Face book API is very complicated. i wish you had an example but thanks a lot.

[...] Javablog » Tips for writing FaceBook applications in Java - So you want to write a FaceBook application using Java? Here are some tips to help get you started [...]

Hi,

Sadly I’m not an expert. I’m also very new to writing facebook apps in Java. There are so many php examples out there it makes me sad :(

I’m still a little confused about session keys and user ids and how we should access them. You mentioned something about accessing the session key from CGI variables. What do you mean by CGI variables? The php examples seem to set the userid and session key as cookie params so I just thought I would have to do a call to getSession to get the facebook session key and then store that in my HttpSession which would in turn store this stuff in cookies on the browser.

Thanks for writing this. It’s getting me on the right track.

To Ron,
When one of your servlets is called via Facebook, it has several form variables passed to it by Facebook. E.g. suppose a user requests http://apps.facebook.com/myapp/myservlet. Facebook will request /myservlet from your server. This request will come with several useful form variables. The one you need is fb_sig_session_key - which is defined in the java library as FacebookParam.SESSION_KEY. You might use code like this to create a FacebookRestClient:

public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
                    HttpServletResponse response) {
        String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());
        if (sessionKey==null) {
            // Not logged in!
        }
        FacebookRestClient client = new FacebookRestClient(API_KEY, SECRET_KEY, sessionKey);
        // Do Facebook stuff...
    }
 
    public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
        doGet(request, response);
    }
}

Hope that helps.

Hi,

I am trying to create a facebook application and have problem getting the session. Facebook throws me “Invalid Parameter” error.

Could you please help.

Thanks a lot,

Krishna

nekin vachhani wrote:

hi there ,

i found your above desc. very much useful to me. but i hv one problem, i have downloaded the java client library from facebook.com site but it has around 100 errors when i make a project under myeclipse web project type. so can you please send me the code of the same if you have it error free one.

Thanks, Nekin

I have the code:

    FacebookRestClient client = new FacebookRestClient("", "");
    int userNow = client.users_getLoggedInUser();

i’m having problems with this, any ideas?

In reverse order…

To Harry,
You’re creating a client without your program keys or a session key. You need to do this instead:

FacebookRestClient client = new FacebookRestClient(API_KEY, SECRET_KEY, sessionKey);

See my reply to Ron above. The api and secret keys are those generated by the Facebook Developer application when you ask to create a new application.

To Nekin,
I had no problems with the client library. I simply copied their .java files into the src folder of a normal Eclipse Java project. Perhaps you are trying to use the client library as a web-app? It isn’t one - though it could be used inside one - it’s just plain old Java.

To Krishna,
I’ll try to help, but it isn’t clear what’s wrong.

  • Are you creating a FacebookRestClient (FRC) using new FacebookRestClient(API_KEY, SECRET_KEY)? FRCs created in this way are pretty much useless and will throw exceptions. Their only use is to generate session keys, but there are easier ways. You need to use the 3 argument constructor, new FacebookRestClient(API_KEY, SECRET_KEY, sessionKey)
  • Are you OK for getting the session key from an http request? When Facebook calls your servlet on behalf of a user, the session key is sent in the request as a form variable. See my reply to Ron (above) for how to extract it.
  • Are you trying to access Facebook independently of a user interaction? E.g. if your app is trying to do a daily update to a user’s FBML. This is a little tricky.

All the best,
Daniel

Where do you get the session key?

I see your response above

Chris Herron wrote:

Have you had any trouble with the java session token? If I have a form in a Facebook canvas page e.g: action="Example.action;jsessionid=123456"

When the form is submitted, it goes via FB which then passes the request on to the callback URL. When this happens though, they do (incorrect) URL encoding on it which loses the semicolon. The full URL ends up being: http:///Example.action%3Bjsessionid%3D123456

With Tomcat, this messes things up because it can no longer resolve a servlet to pass the request to, never mind locate the session.

Have you encountered this problem? If so, were you able to get around it?

I’m afraid I can’t help re. Tomcat as I don’t use Tomcat. If anyone reading this knows about this problem, please post your advice here & I’ll forward it to Chris.

Syed Shah wrote:

I created a login servlet to access the facebook api and utilzing the rest client however I am getting an error in the try block. See the code snippet below:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
String apiKey = getServletConfig().getInitParameter("API_KEY");
String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
        
FacebookRestClient facebookRestClient = null;
HttpSession session = request.getSession();
String sessionKey = (String)session.getAttribute("facebookSession");
String token = request.getParameter("auth_token");        
        
if (sessionKey != null && sessionKey.length() >0) {
facebookRestClient = new FacebookRestClient(apiKey, secretKey, sessionKey);
}
else if (token != null){
facebookRestClient = new FacebookRestClient(apiKey, secretKey);
facebookRestClient.setIsDesktop(false);
            
try {
sessionKey = facebookRestClient.auth_getSession(token);
session.setAttribute("facebookSession", sessionKey);
}
catch (FacebookException e){
e.printStackTrace();
}
}       
else {
response.sendRedirect("http://www.facebook.com/login.php?api_key="+ apiKey + "&v=1.0");
return;     
}
response.getWriter().println("Hello World!");
    }

….and I get the following error:

19:06:34,937 ERROR [Engine] StandardWrapperValve[Login]: Servlet.service() for servlet Login threw exception java.lang.NoSuchMethodError: org.w3c.dom.Document.normalizeDocument()V at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:263) at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:219) at com.facebook.api.FacebookRestClient.auth_getSession(FacebookRestClient.java:1078)

I too was disappointed at the poor docs, so I’ve been gradually documenting the problems I’ve hit and how to work around them here:

(basic starting points) http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-1/

and here:

(all about logins, authentication, example code, etc) http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-2/

…and I’ll be doing another couple of posts soon with more advanced stuff and more examples.

Once you get past a certain point, it’s good, but getting that far is really tough.

Adam

To Syed Shah….

I had a similar problem when using JBoss as my application server. Turns out the that the org.w3c.dom library that was being loaded by the application server was different to that used in the Facebook API classes. I solved the problem by updating the these jars (xercesImpl.jar and xml-apis.jar) in the application server. Warning - there is a possibility that updating these jars in your application server may cause other problems but it worked fine in my instance.

Hope this helps.

Amit Sharma wrote:

I was also facing the same problem .I was using Jboss 4.0.1 and jdk1.5 the problem is with xmlapis.jar in the $Jboss/lib/endorsed..i updated it and now its working.

Syed Shah wrote:

Thanks Oisin/Amit for the feedback. Updating xml_apis.jar did the trick however, when I proceeded to do the third facebook api tutorial on the Screencast blog, I got yet another error. See below. Is this another xml jar file issue? Oisin, I know in your previous entry, you noted the “possibility that updating these jars in your application server may cause other problems”……let me know if you guys ran into this. Thanks.

13:26:11,734 INFO [WebService] Using RMI server codebase: http://ACNCND7210901:8083/ 13:26:12,000 INFO [NamingService] Started jndi bootstrap jnpPort=1099, rmiPort=1098, backlog=50, bindAddress=/0.0.0.0, Client SocketFactory=null, Server SocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076 13:26:12,125 WARN [XMLLoginConfigImpl] End loadConfig, failed to load config: file:/C:/jboss-4.0.1sp1/server/default/conf/login-config.xml org.jboss.security.auth.login.ParseException: Encountered ” …

at org.jboss.security.auth.login.SunConfigParser.generateParseException(SunConfigParser.java:389)
at org.jboss.security.auth.login.SunConfigParser.jj_consume_token(SunConfigParser.java:327)
at org.jboss.security.auth.login.SunConfigParser.config(SunConfigParser.java:98)
at org.jboss.security.auth.login.SunConfigParser.parse(SunConfigParser.java:57)

I was getting the normalizeDocument exception and in order to overcome this I forced the application to use the xerces parser with this line:


System.setProperty("javax.xml.parsers.DocumentBuilderFactory","org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); 

Harry,

Here is a code snippet of what I am doing to get the session key. Hope it helps.

Jim


        HttpSession session = request.getSession();
        String sessionKey = (String)session.getAttribute("facebookSession");
        if (sessionKey == null)
        {
            sessionKey = request.getParameter("fb_sig_session_key");
        }
        String token = (String)request.getParameter("auth_token");
        
        if (sessionKey != null && sessionKey.length() > 0)
        {
            System.out.println("Have a sessionKey: " + sessionKey);
            facebookRestClient = new FacebookRestClient(apiKey, secretKey, sessionKey);
        }
        else if (token != null)
        {
            System.out.println("Have a token (" + token + ") with no sessionKey");
            facebookRestClient = new FacebookRestClient(apiKey, secretKey);
            facebookRestClient.setIsDesktop(false);
            try
            {
                sessionKey = facebookRestClient.auth_getSession(token);
                System.out.println("sessionKey: " + sessionKey);
                if (sessionKey == null)
                {
                    System.out.println("Sending to logon 1");
                    sendToLogon(response, apiKey);
                    return;
                }
                session.setAttribute("facebookSession", sessionKey);
            }
            catch (FacebookException e)
            {
            e.printStackTrace();
            }
        }
        else
        {
            System.out.println("Sending to logon 2");
            sendToLogon(response, apiKey);
            return;
        }


...


    private void sendToLogon(HttpServletResponse response, String apiKey) throws IOException {
        URL url = new URL("http://www.facebook.com/login.php?api_key=" + apiKey + "&v=1.0");
        doRedirect(response, url);
        return;
    }   


Adam- I’m having a problem viewing the web page with the tutorial that you posted links for (http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/) when I go to the page, it isn’t displayed correctly and you can’t scroll down and actually read the article… I’m on IE7 xp sp2. Please adivse, I finally found what looks to be a useful tutorial and I can’t read it!

Hi Guys, I’m new to developing apps for Facebook, and currently doing some research.

I just want to know why you guys recommend using Java 5 or higher. Is it because the Facebook client makes use of Java 5 code? Are there any other reasons?

Our servers are currently on 1.4 and updating to Java 5 might still take a while. Is this a show stopper for me?

Jean… Java 5 introduced some awesome language features: Generics and enums. If you ever use generics to add type to container objects, then you’ll never want to go back to casting. enums are used in the facebook API.

MIckle John wrote:

Hello, I need to build a desktop application using java to upload video files on facebook. I am a newbie in this field. Anyone can help me?

Did anyone encounter the following error in JBOSS? Is this an Eclipse issue?

13:26:11,734 INFO [WebService] Using RMI server codebase: http://ACNCND7210901:8083/ 13:26:12,000 INFO [NamingService] Started jndi bootstrap jnpPort=1099, rmiPort=1098, backlog=50, bindAddress=/0.0.0.0, Client SocketFactory=null, Server SocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076 13:26:12,125 WARN [XMLLoginConfigImpl] End loadConfig, failed to load config: file:/C:/jboss-4.0.1sp1/server/default/conf/login-config.xml org.jboss.security.auth.login.ParseException: Encountered ” …

at org.jboss.security.auth.login.SunConfigParser.generateParseException(SunConfigParser.java:389) at org.jboss.security.auth.login.SunConfigParser.jj_consume_token(SunConfigParser.java:327) at org.jboss.security.auth.login.SunConfigParser.config(SunConfigParser.java:98) at org.jboss.security.auth.login.SunConfigParser.parse(SunConfigParser.java:57)

Nate - should be working properly in IE7 now. If not, download a working browser, like Firefox.com, and post on the blog with problems, that way I’ll at least get an email telling me you’ve posted :). It’s pretty off-topic to be posting problems with MY site on someone else’s blog :).

And hey, you might even find you prefer FF to IE7 ;)

Dear Friends, Thank you for the nice tips. Can anyone help me for getting information of all facebook friends? I want to display all the friends information of a logged in user. Thanks & Regards, Afzal

Is it posible to do all of this with only javascript and not java servets and classes.. just having a single FacebookAPI.js that your application can all most of the FB API from?

eg

 
<a href="#" rel="nofollow">Show My Friends</a>

the

 thing dint work :( ok here is the code 

Show My Friends

I have an issue getting the user’s id. I have the following code running in a JSP on a tomcat.





userid:

authtoken:

sessionkey:

Also, I embedded this into facebook using IFRAME, and I call it by apps.facebook.com/myapp/index.jsp

I see a number for auth token and session key, however, the user is always -1 and is not my facebook user id. Any ideas?

I have an issue getting the user’s id. I have the following code running in a JSP on a tomcat.



String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

FacebookRestClient client = 
    new FacebookRestClient(API_KEY, SECRET_KEY, sessionKey); 
    
String auth = client.auth_createToken();
int uid = client.auth_getUserId(auth);

------------

userid:

authtoken:

sessionkey:

Also, I embedded this into facebook using IFRAME, and I call it by apps.facebook.com/myapp/index.jsp

I see a number for auth token and session key, however, the user is always -1 and is not my facebook user id. Any ideas?

Apparently this blog does not like jsp code bracket and %’s. Rest assured the above code has the proper brackets etc.

Thanks for such a wonderful description, I need it. but one basic question where can i host my web application, First I just want to play around facebook application and for that i dont want to pay money to any hosting service.

Kindly let me know if you know any free hosting service for java web application for facebook.

Thanks Amit

I am looking for a small self-contained example Java APPLET that uses the facebook_java_client library to interact with Facebook.

I am looking for an applet that would run in a web page on an outside server, rather than being “embedded” inside a Facebook page using FBML, etc.

I am planning to write an interactive graphics applet (which wouldn’t work inside a Facebook page anyway).

I have been able to write a Java applet that communicates through with Facebook through an intermediate PHP server. i.e., JAVA <-> PHP <-> Facebook. But this approach is relatively slow and wastes bandwidth on the server, since a (signed) JAVA applet could communicate directly with Facebook.

If anyone has a small working example that does ANYTHING AT ALL, it would be a wonderful starting point. For instance, a JAVA applet that simply checked the visitor was logged into Facebook, and then queried the server to get their name, or picture, or list of friends, … would be great.

thanks, djones

Hi,

Getting below error. My callback url is a jsp page with this tag inside

Errors while loading page from application Runtime errors: HTML tag not supported: “title” HTML tag not supported: “meta” HTML tag not supported: “link” HTML tag not supported: “link” HTML tag not supported: “link” HTML tag not supported: “body”

fb:name uid=”586231789″ capitalize=”true”

I’m attempting to use the facebook API and its java libraries with tomcat and I’m having an invalid signature error that I can’t seem to work around. I would very much appreciate any feedback/ideas anyone might have.

Super simple code:

String api_key = "xxxxxxxxxxxxxxxxxxxxxxxxx";
String secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String authToken = (String)request.getParameter("auth_token");
 
FacebookRestClient client = new FacebookRestClient(api_key, secret);
client.setDebug(true);
String sessionKey = client.auth_getSession(authToken);
Document d= client.friends_get();

Getting the sessionKey works great, but the call to get the friends results in “Incorrect signature”. A signature is being generated deep in the pre-fab class which matches my own MD5 sum.

I’m stumped. Thanks for any help you can offer.

christophe wrote:

Really great tutorial ! One question for you: I want to use the facebook.data.getUserPreference API (does not look to be already in the JAVA API, but easy to add anyway). My concern is that I need to get this data for the user profile, not for the logged in user as I want to store application configuration information (The profile user can choose some parameters for the application). How do I do that ? Does someone have a code sample ?

Thanks a lot

christophe wrote:

Sorry, my mistake. I just realized that only the profile owner runs the application: viewers just get the app “content” from facebook cache.

This is a strong limitation as, as an application provider with highly dynamic content, we need to push refreshed content to the profile for users who installed our app. But, this is it, I guess ;-)

Some of the comments in the article are incorrect. For example, you state:

“Your contents will be adapted before being sent back to the user. Mostly you don’t need to worry about this — it works nicely. But be aware that JavaScript is not allowed That means if you’re using an AJAX platform, it won’t work within FaceBook.”

This is true for apps configured to run in FBML mode only. If you set your application to run in Iframe mode, you can use javascript, AJAX, and everything else that you could normally use inside of a standard web application.

Also, here is a version of the Java API that is more actively maintained than the official one:

http://code.google.com/p/facebook-java-api/

…it also saves you from having to deal with the Document object returned by most API calls (unless you prefer dealing with it, in which case you still can).

Great posts, it clears up a lot of confusion regarding authentication using Java.

However, writing a loging servlet and making all the facebook requests go through it is not clean since it means you need to also write a routing logic in your login servlet to go to the specific servlet after successful authentication. The ideal solution will be to move this to “framework” code and intercept all the requests before it reaches application servlet. Check this out - http://theliveweb.net/blog/2007/10/31/facebook-authentication-using-java/

Thanks a million for the explanation on getting the SessionKey from the CGI variables. I wasted endless time trying to figure out why I couldn’t get the session key when instantiating the FRC obj with only the 2 params.

Very helpful!

Has anyone figured out why Tomcat has issues getting the various fields, i.e. userid, authtoken,sessionkey?

I’ve written a test app in Java and it runs fine on a Windows box using Tomcat. But when I run it on a Linux box the above fields return null.

Any help is appreciated.

To solve the problem I changed the following:

FROM:

String sessionKey = (String) session.getAttribute(”facebookSession”);

TO:

String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

Recently i have found that FacebookRestClient.notificationssendRequest() does not exists in the new API. i have tried with the notificationssend() ,where the content i sent is

“Get this fabulous Game? <fb:req-choice url=’http://www.facebook.com/add.php?apikey=” + api_key + “‘ label=’Add The Application’ > “

But i dont get anything for the <fb:req-choice ..> tag.

can anyone help me how can i send invitation from my java code .

Thanks in advance

@Rabbi: Facebook recently changed the viral invite API — breaking backwards compatibility. The new API is better though. See http://wiki.developers.facebook.com/index.php/Fb:request-form for details.

I too am getting error #104, “Incorrect signature”

The POST, which is exposed in the console with DEBUG=true, looks like this:

http://api.facebook.com/restserver.php?
  sessionkey=key>&
  callid=id>&
  sig=&
  apikey=key>&
  method=facebook.friends.get&format=xml&
  v=1.0

This is straight from the ExampleClient.java run method, with no tweaks to the code (other than changing the DEBUG constant to true). I know the userid, session, etc is good because two requests are made successfully before this point.

I am just playing with this API for the first time, and a bit discouraged with the lack of error documentation. Facebook’s error page (http://wiki.developers.facebook.com/index.php/Error_codes) doesn’t even include error #104.

I’ve seen this on several posts, and nobody seems to have an answer.

Thanks in advance,

Rob

I just answered my own question… since I am running this as a desktop app, I need to tell the API. I set the following parameter in the settings.conf file and it now works as expected…

desktop = 1

Guess that was sort of a no brainer. =)

I am facing a problem for retrieving logged in users information as well as friends information. It is throwing xml parse exception. The code was working perfectly before november but not same code does not work, throws exception. Need help badly.

The code is pasted below.

/** * @param request * @param response * @return * @throws Exception * Updated by Afzal date: 16 09 2007 */ public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // System.setProperty(”javax.xml.parsers.DocumentBuilderFactory”,”org.apache.xerces.jaxp.DocumentBuilderFactoryImpl”); String next = “Main”; SearcherMailSendBean nextBean = (SearcherMailSendBean)getBusinessBean(request, “bd.co.afzal.ikab.command.SearcherMailSendBean”); String req=request.getParameter(”request”); nextBean.setRequest(request); FacebookRestClient facebookRestClient=null; String apiKey=”535d1513d0e592e464d2970d5ac270e2″; nextBean.setData(”apikey”,apiKey); String secretKey=”403c379634109affe28673343d842083″; HttpSession session=request.getSession(); String sessionKey=(String)session.getAttribute(”facebookSession”); String token=request.getParameter(”authtoken”); if (sessionKey == null) { sessionKey = request.getParameter(”fbsigsession_key”); }

    if(sessionKey!=null&&sessionKey.length()>0){
      facebookRestClient=new FacebookRestClient(apiKey,secretKey,sessionKey);
    }else if(token!=null){
      facebookRestClient=new FacebookRestClient(apiKey,secretKey);
      facebookRestClient.setIsDesktop(false);



    try{
      sessionKey=facebookRestClient.auth_getSession(token);
      sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

      session.setAttribute("facebookSession",sessionKey);

    }catch(FacebookException e){
      e.printStackTrace();
    }
    }else{
        nextBean.setData("req",req);
        return "login";
    }
    nextBean.setData("req",req);
    populateFacebookFriendList(request,facebookRestClient,nextBean);
    return "main";
}
private void populateFacebookFriendList(HttpServletRequest request,FacebookRestClient facebookRestClient,SearcherMailSendBean nextBean){


     try{
       int myId=facebookRestClient.users_getLoggedInUser();
       EnumSet<ProfileField>fields=EnumSet.of(com.facebook.api.ProfileField.NAME,
          com.facebook.api.ProfileField.PIC);
       Collection<Integer>users=new ArrayList();
       users.add(myId);

       Document d=facebookRestClient.users_getInfo(users,fields);
       String name=d.getElementsByTagName("name").item(0).getTextContent();
       String picture=d.getElementsByTagName("pic").item(0).getTextContent();
       nextBean.setData("name",name);
       nextBean.setData("picture",picture);
       //d=facebookRestClient.friends_get();
       d= facebookRestClient.friends_get();
       NodeList userIDNodes = d.getElementsByTagName("uid");
       int fCount = userIDNodes.getLength();
      // int numOfFriends=d.getChildNodes().getLength();
       request.setAttribute("name",name);
       request.setAttribute("picture",picture);
       request.setAttribute("friendCount",Integer.toString(fCount));
       nextBean.setData("friendCount",Integer.toString(fCount));

       List<Integer> friends = new ArrayList<Integer>();
       for(int i=0; i<fCount; i++) {
           Node node = userIDNodes.item(i);
           String idText = node.getTextContent();
           Integer id = Integer.valueOf(idText);
           friends.add(id);
       }
       String req="";
       if(nextBean.isSetted("req"))
            req=nextBean.getData("req");
     //  if(req!=null&&(req.length()>0&&req.equalsIgnoreCase("invite"))){
      //    facebookRestClient.notifications_send(friends,"Hello..welcome to IKAB","Get this fabulous application <BR><a href='http://www.facebook.com/add.php?api_key="+nextBean.getData("api_key")+"label=Add application'");
      // }
       fields=EnumSet.of(com.facebook.api.ProfileField.NAME,
                  com.facebook.api.ProfileField.PIC,
                  com.facebook.api.ProfileField.ABOUT_ME
                  );
       d=facebookRestClient.users_getInfo(friends,fields);

       for(int i=0;i<fCount;i++){


         //  
           name=d.getElementsByTagName("name").item(i).getTextContent();
           picture=d.getElementsByTagName("pic").item(i).getTextContent();
           String me=d.getElementsByTagName("about_me").item(i).getTextContent();
           nextBean.setData("name"+i,name);
           nextBean.setData("picture"+i,picture);
           nextBean.setData("me"+i,me);
           nextBean.setData("friends"+i,Integer.toString(i)); 
       }

    }catch( FacebookException e){
      e.printStackTrace();
    }catch(IOException e){
    }


    }

Thanks & regards Md. Afzalur Rashid

Exactly the clue I needed — I had completely missed the fact that there was another constructor to FacebookRestClient, that took the session key. Once I started passing that in (after two days of beating my head against it), everything worked like a charm. Thanks!

Hi all, I m pure Java guy so help me with that. I have tried to login and show up frnds and that work…my app has the following flow: hit the app url: Login(if not) –> show a page and let user do some activity –> show frnds and select them and share –> show the result. Now my question is how do I go abt it…how many servlets and jsps(I have done the login servet…callback url)…where to store data etc and code snippets to select and share with frnds….Can anyone help me ASAP? thanx in advance

I am getting the parser exception: java.lang.NoSuchMethodError: org.w3c.dom.Document.normalizeDocument()V

osin/syed, can anyone please tell me which version of (xercesImpl.jar and xml-apis.jar) to be used.

Thanks Vinuta

Hi all, it is not clear for me do we need to get fbook client like facebookRestClient= new FacebookRestClient(apiKey,secretKey,sessionKey); or we can create it once at logging time and save it on session?

Dear All, I think this page is become very old. There are lots of changes in the api. Now we need to use FacebookXmlRestClient instead of FacebookRestClient….There are lot more changes…Can anybody help for new Api?

Hi all, have you ever experience the problem when upload photo with a caption specified in unicode characters in utf8 format for example - none english characters will always leads to an error said “com.facebook.api.FacebookException: Incorrect signature”. If I coded the caption into quoted-printable format, and/or add “Content-Transfer-Encoding: quoted-printable” to post data, it can be uploaded, but the caption becomes the encoded one, not expected decoded one when view from the photos application.

is here someone can give some hints?

hiii guys

thanx for helping me in many ways… but still i m facing problem with session key… Here i am getting session key “null” can any one tell me how to solve this problem.

i’ve already done these changes

from:- sessionKey = (String)session.getAttribute(”facebookSession”);

To:- sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

Plz help me…

Rajib Datta wrote:

Hi,

I am trying to create a facebook application and have problem getting the session. Facebook throws me “Invalid Parameter” error. Exception in thread “main” com.facebook.api.FacebookException: Invalid parameter at com.facebook.api.FacebookXmlRestClient.parseCallResult(FacebookXmlRestClient.java:106) at com.facebook.api.FacebookXmlRestClient.parseCallResult(FacebookXmlRestClient.java:1) at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:858) at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:631) at com.facebook.api.FacebookXmlRestClient.auth_getSession(FacebookXmlRestClient.java:74) at com.facebook.api.ExampleClient.main(ExampleClient.java:94)

Could you please help.

Thanks a lot,

I have exactly the same problem regarding the encoding of the caption in the photo_upload method that Davve wrote about. For me the swedish letters ‘öäåÅÄÖ’ is not accepted nor do I find any way to encode them so that they turn up correct in FB. Does anyone have some idea on what to do?

Thanks in advance!

Leave a comment

Markdown is supported.

To include code snippets in your comment, use

<pre><code># lang java
... code here ...
</code></pre>

or use 4 spaces at the start of the line instead of using code and pre tags.

Comment feed: RSS