Send a Tweet from Flash/Flex

I’ve played with all of the Twitter API systems out there, and I find them bulky and unpleasant to instantiate. If all you want to do is send a tweet from a flash project, this is the method you need.

Note: You’ll need a copy of the Base64 Class, which is available here or in the link below (This is excellent work, by the way).

import com.dynamicflash.util.Base64;
 
public function sendTweet(username:String, password:String, text:String):void
{
	var urlRequest:URLRequest = new URLRequest('http://api.twitter.com/1/statuses/update.xml');
	var urlLoader:URLLoader = new URLLoader();
 
	var vars:URLVariables = new URLVariables();
	vars.status = text.substr(0, 140);
 
	urlRequest.method = URLRequestMethod.POST;
	urlRequest.data = vars;
 
	urlRequest.requestHeaders = [new URLRequestHeader("Authorization", "Basic " + Base64.encode(username + ":" + password))];
 
	urlLoader.load(urlRequest)
}

If you pass a valid username, password, and string to this method, it should update the status to what you specify.

Finally, you’ll need to create a crossdomain.xml file for use with Twitter otherwise you’ll get security exceptions. If you want to test the functionality, you can run the SWF outside the HTML file, which doesn’t require the same security settings or you can add your project folder to the allowed list of sites using the Settings Manager (I usually add my whole hard drive to this — ‘c:\” or “/” on a Mac).