Flex – Playing with Twitter API and solving the cross-domain problem

March 27th, 2009 | Author: Sunny

Today I wrote a small and simple Flex program with Twitter API. Here is my code:


<?xml version="1.0" encoding="utf-8"?>
  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundImage="@Embed(source='image/twitter_bg.png')" height="50" width="850" layout="absolute" creationComplete="twitterService.send()">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;

[Bindable]
private var Feed:Object;

public function twitterHandler(event:ResultEvent):void {
Feed = event.result.user;
}

]]>
</mx:Script>
<mx:HTTPService id="twitterService" url="proxy.php" result="twitterHandler(event)" />
  <mx:HBox width="800" height="41" verticalCenter="1" x="0" verticalAlign="middle">
  <mx:Spacer x="0" y="0" width="15"/>
  <mx:Image source="@Embed(source='image/twitter_logo_header.png')" width="126" height="25"/>
  <mx:Image source="{Feed.profile_image_url}" width="30" height="30"/>
  <mx:Label text="{Feed.screen_name}" fontSize="16" color="#2896AD" width="83"/>
  <mx:Label text="{Feed.status.text}" width="498" fontSize="12" color="#084755"/>
  </mx:HBox>
  </mx:Application>

and you can see the result here: http://sunnycyk.hk/twitter/

It may look easy, but actually it takes me sometime to figure out how to make it works. The code was working fine in debug mode with Flex, but it did not work on release mode. I was wondering why and searching on internet, and finally figure out it is because of security reason.

There are couple methods you can try, but I just used a easy way to do it by adding a proxy.php file. What proxy.php does just requests data from the remote domain site (for my case, it is “http://twitter.com/users/show/skyc999.xml”), and regenerates the output so that your flash player will think that you are working with a local XML file.

When my flash file runs, it will call proxy.php. Then proxy.php will grab XML file from Twitter, and generate the XML output to my flash file. Because my flash file only calls the local file, it does not voliate the flash player security policy setting, and everything works again!

The proxy.php only contains two line of code:


<?php
$dataURL = "http://twitter.com/users/show/skyc999.xml";
readfile($dataURL);
?>

If you are a twitter user, you can try my program(download it?) and replace the skyc999 in $dataURL with your screen name.

This example just gives a basic idea how to work with cross-domain files and Twitter API. Hope it can help you (and me) :)

Category: Flex | Tags: :, | Leave a Comment

Leave a Reply

You must be logged in to post a comment.