Here’s an AS3 example using the url shortening service bit.ly
Bit.ly is a utility that allows users to shorten a long URL, share it, and then track the resulting usage.
Why would you want to shorten your Url?
Url shortening makes it easier to include the link in an email or Twitter post without it breaking or taking up space. Bit.ly basically redirects a click from the short url to the destination URL using a A 301 redirect. Bit.ly doesn’t re-use or modify links, so the redirects can be considered permanent. Every bit.ly link has an info page, which reveals the number of related clicks and other relevant data. You can get to the info page simply by adding a “+” sign to the end of the link, for example http://bit.ly/clebaM+ .
Click on the ‘Create Short URL’ button below to display the link.
There you go, a short url link created from the http://www.flickr.com/photos/unaesthetic/4513005444/ long url.
The first thing you need to do, to get the example application up and running, is register with bit.ly to get a free user account and api key.
Now lets take a look at the classes:
Main.as
The Main.as document class sets up the user interface in the flash example. The init() method is where we instantiate the class which communicates with the bit.ly api.
/****************************
* Manuel Gonzalez *
* design@stheory.com *
* www.stheory.com *
* www.codingcolor.com *
*****************************/
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import com.business.Bitly;
public class Main extends Sprite {
private var _bitly:Bitly;
private var _bitlyCallback:Object;
private var BITLY_LOGIN:String = "xxxxxxxx";//your own username
private var BITLY_KEY:String = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";//your Api Key
private var _createShortUrlButton:Button;
private var _urlInput:TextInput;
private var _shortUrl:String;
private var _displayUrlTextField:TextField;
private var DEFAULT_URL:String = "http://www.flickr.com/photos/unaesthetic/4513005444/";
public function Main(){
init();
_urlInput = ti;// instances are already on stage
_urlInput.x = 15;
_urlInput.y = 105;
_urlInput.width = 300;
_urlInput.text = DEFAULT_URL;
_createShortUrlButton = cb;// instances are already on stage
_createShortUrlButton.label = "Create Short URL";
_createShortUrlButton.x = _urlInput.x + _urlInput.width + 10;
_createShortUrlButton.y = _urlInput.y;
_createShortUrlButton.addEventListener(MouseEvent.CLICK, createButtonOnClick,false, 0, true);
_createShortUrlButton.buttonMode = true;
_displayUrlTextField = new TextField();
_displayUrlTextField.x = 25;
_displayUrlTextField.y = _urlInput.y + 70;
_displayUrlTextField.selectable = false;
_displayUrlTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(_displayUrlTextField);
//make bitly graphic into button
bkg.btn.buttonMode = true;
bkg.btn.addEventListener(MouseEvent.CLICK, bitlyButtonOnClick,false, 0, true);
}
/*
Method:init()
Parameters:
Returns:
*/
public function init():void
{
_bitly = Bitly.getInstance();
_bitly.login = BITLY_LOGIN;
_bitly.apiKey = BITLY_KEY;
}
/*
Method:createButtonOnClick
Parameters:
event:MouseEvent
Returns:
*/
private function createButtonOnClick(event:MouseEvent):void
{
var urlToShorten:String = _urlInput.text;
createBitlyUrl(urlToShorten);
}
/*
Method:bitlyButtonOnClick
Parameters:
event:MouseEvent
Returns:
*/
private function bitlyButtonOnClick(event:MouseEvent):void
{
var URLReq:URLRequest = new URLRequest("http://bit.ly/m");
try {
navigateToURL(URLReq, "_blank");
} catch (event:Error) {
//trace(event);
}
}
/*
Method:createBitlyUrl
Parameters:
inUrl:String
Returns:
*/
private function createBitlyUrl(inUrl:String):void
{
_bitly.shortenUrl(inUrl);
_bitly.addEventListener(Event.COMPLETE,bitlyCompleteHandeler,false, 0, true);
}
/*
Method: bitlyCompleteHandeler
Parameters:
event:Event
Returns:
*/
private function bitlyCompleteHandeler(event:Event):void
{
_bitly.removeEventListener(Event.COMPLETE,bitlyCompleteHandeler);
_shortUrl = _bitly.shortUrl;
displayShortenUrl();
}
/*
Method: displayShortenUrl
Parameters:
Returns:
*/
private function displayShortenUrl():void
{
_displayUrlTextField.htmlText = makeClickable(_shortUrl);
}
/*
Method: makeClickable
Parameters:
inStr:String
Returns: String
*/
private function makeClickable(inStr:String):String
{
var str:String = inStr;
var hasLink:Boolean = false;
var nstr:Array = str.split(' ');
var len:int = nstr.length;
for( var i:int = 0; i < len; i++ )
{
var n = (nstr[i]).indexOf("http://");
if( n > -1 ){
nstr[i] ="<font color=\"#0000dd\"><A HREF='"+ nstr[i]+ "' target='_blank'><U>"+ nstr[i]+"</U></A></font>";
hasLink = true;
}
}
if(hasLink){
return nstr.join(' ');
}else{
return str;
}
}
}
}
Bitly.as
The Bitly.as class calls upon the bit.ly api which returns a shorten url. I use the Adobe Serialization classes (included in source download) to handle the default Json format. The Bitly.as class is pretty bare bones, since my only use to date is to shorten a long url.
/****************************
* Manuel Gonzalez *
* design@stheory.com *
* www.stheory.com *
* www.codingcolor.com *
*****************************/
package com.business{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import com.adobe.serialization.json.JSON;
public class Bitly extends Sprite {
private static var _instance:Bitly;
private var _login:String;
private var _apiKey:String;
private var _url:String;
private var _bitlyApi:String="http://api.bit.ly/shorten?version=2.0.1&longUrl=";
private var _loader:URLLoader;
private var _shortenUrl:String;
public function Bitly(singletonEnforcer:SingletonEnforcer) {
}
/*
Method: getInstance
Returns:Bitly
*/
public static function getInstance():Bitly {
if (_instance == null) {
_instance=new Bitly(new SingletonEnforcer );
}
return _instance;
}
///////////////////////////////////////// setters & getters ///////////////////////
public function set login(inStr:String):void {
_login=inStr;
}
public function get login():String {
return _login;
}
public function set apiKey(inStr:String):void {
_apiKey=inStr;
}
public function get apiKey():String {
return _apiKey;
}
public function get shortUrl():String {
return _shortenUrl;
}
//////////////////////////////////////////////////////////////////////////////////
/*
Method:shortenUrl
Parameters:
inUrl:String
Returns:
*/
public function shortenUrl(inUrl:String):void {
_url=escape(inUrl);
getBitlyURL();
}
/*
Method:getBitlyURL
Parameters:
Returns:
*/
private function getBitlyURL():void {
var path:String=_bitlyApi + _url + "&login=" + _login + "&apiKey=" + _apiKey;
_loader=new URLLoader ;
configureListeners();
_loader.load(new URLRequest(path));
}
/*
Method: configureListeners
Parameters:
Returns:
*/
private function configureListeners():void {
_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,handleBitlyStatus,false, 0, true);
_loader.addEventListener(IOErrorEvent.IO_ERROR,handleBitlyError,false, 0, true);
_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,handleBitlyError,false, 0, true);
_loader.addEventListener(Event.COMPLETE,handleBitlyComplete,false, 0, true);
}
/*
Method: removeListeners
Parameters:
Returns:
*/
private function removeListeners():void {
_loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS,handleBitlyStatus);
_loader.removeEventListener(IOErrorEvent.IO_ERROR,handleBitlyError);
_loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,handleBitlyError);
_loader.removeEventListener(Event.COMPLETE,handleBitlyComplete);
}
/*
Method: handleBitlyComplete
Parameters:
event:Event
Returns:
*/
private function handleBitlyComplete(event:Event):void {
removeListeners();
var bitlyObj:Object = JSON.decode(event.target.data);
var url = unescape(_url);
if (bitlyObj.statusCode == "OK") {
_shortenUrl = bitlyObj.results[url].shortUrl;
dispatchEvent(new Event(Event.COMPLETE));
} else {
trace("ERROR");
}
_loader = null;
}
/*
Method: handleBitlyStatus
Parameters:
event:HTTPStatusEvent
Returns:
*/
private function handleBitlyStatus(event:HTTPStatusEvent):void {
//trace('BITLY status: ' + event);
}
/*
Method: handleBitlyError
Parameters:
event:Event
Returns:
*/
private function handleBitlyError(event:Event):void {
//trace('Getting BITLY url failed with error: ' + event);
}
}
}
internal class SingletonEnforcer {
}
I currently used the Bitly class in an application that enabled users to share a custom page via twitter.
FYI I’m using a link to Chris Brennan’s flickr. image.
Enjoy!
Download Source:
Bit.ly AS3 exmaple (157)
found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later
Great writeup, I’m going to use your bit.ly and serialization classes and wrap my own design around the functionality. Worked a treat!
[...] AS3 & bit.ly the URL shortener [...]
I didn’t know how i found you site. But swear, I’m so using your Bitly class. Thank you berymuch.
This is awesome. I’m having a little problem though. I have a button that i’m setting up so that when clicked, it navigates to the following url : http://twitter.com/home?status= and within the status query, it should have the short url. My button click function looks like this:
_bitly.shortenUrl(http://www.url_i_wanna_shorten.com);
_bitly.addEventListener(Event.COMPLETE, bitlyCompleteHandeler,false, 0, true);
then in my bitlyCompleteHandeler function i have:
_bitly.removeEventListener(Event.COMPLETE,bitlyCompleteHandeler);
_shortUrl = _bitly.shortUrl;
bitlyUrlRequest = new URLRequest(“http://twitter.com/home?status=” + _shortUrl);
navigateToURL(bitlyUrlRequest, “_blank”);
I don’t even make it to the bitlyCompleteHandeler function so i don’t even know if the code there works. Any ideas on what I’m doing wrong?
Hi James,
Are you getting back a valid shorten URL from Bitly? Add a trace statement in the Bitly class in the handleBitlyComplete method, to make sure you are getting a response from the Bitly server. ALSO, flash will not allow you to spawn a URL call with out an explicit button press.
Manuel