Displaying Facebook Profile Images with the Facebook Toolkit

I had a hankering for some code so I thought I would finish off the Facebook profile image support in the new Facebook Toolkit launching in support of the Dreamforce session, Leveraging Public Social Networks

I realized that my last few posts had been heavy on the thinking and light on the code. After working with Sandeep and Jeff on their Dreamforce session, Leveraging Public Social Networks (make sure you sign up for it, it rocks!) I had me a hankering for some development.

In support of Sandeep and Jeff’s session we will be making the new Facebook toolkit available for download. The net result was that I had to finish off the getting started article and tie up a few loose ends. One of these loose ends was write the profile image component. The good news is that the toolkit is designed well and easily supports new objects and extensions so putting the plumbing in place was pretty easy:

1. Write a Component 

Components are a great practice to encapsulate your code, and make developing Visualforce pages a snap:

 

<c:FacebookProfilePicture fbid="717838202" clientid="136520473033312" width="60" height="60" />

 

2. Update the FacebookUser object

/*** Get Profile Pic*/
public String getProfilePicture(){
this.doAPICall(this.id, 'picture',null);
return this.result.data.getValue('data').values[0].obj.getString('url');
}

3. Update the FacebookObject superclass.

This was where things got a little sticky to start with. Apparently when you make a Facebook Graph API call to  get the image with a URL like graph.facebook.com/717838202/picture it actually does a temporary redirect to another URL (In my case, http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs341.snc4/41369_717838202_1756_q.jpg – I can’t help but wonder if Mark Zuckerberg learnt from his Face Mash site). Thankfully 302’s (the code for a temporary HTTP redirect) store the redirect location in a header, “Location”, as part of the HttpRedirect.  

With a little bit of Apex magic, I was back in business:

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
HttpResponse res = h.send(req);
String response = res.getBody();
//fb returns a 302 temp redirect with the url for the profile image
if(res.getStatusCode() == 302)
response = '{"data": [{"url": "'+res.getHeader('Location')+'"},]}';
else
this.result.jsonString = response;

The result, thanks to the toolkit, is a very easy way to drop Facebook profile images into your Visualforce page:

If you are already registered for Dreamforce, make sure you register for the Leveraging Public Social Networks session at Dreamforce and learnhow to get start developing with the Facebook toolkit!

 

Leave your comments...

Displaying Facebook Profile Images with the Facebook Toolkit