I have been starting to plan for my next project to come, and felt the need for a function that would use the bit.ly API to shorten URLs for me.
I found a nice Python example over at http://tux-log.blogspot.com, but was not possible to find any AS3 examples. So I spent the evening making my own.
Hope you like it, it’s way from perfect so please feel free to comment!
/**
* Class ShortenURL
* Author: Olle Dahlstrom(olle.dahlstrom@gmail.com)
* Takes a URL and calls the bit.ly API to shorten it.
* You need to have a bit.ly username and API Key(get it at http://bit.ly/), I have my stored in a Config class file.
*
* Example Code
* import net.subelement17.ShortenURL
* var _url:ShortenURL = new ShortenURL();
* _url.call('http://subelement17.net/blog', giveMeTheUrl);
* function giveMeTheUrl(res:String):void)
* {
* //do something with the result....
* }
*/
package net.subelement17
{
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
public class ShortenURL
{
private var apiKey:String = new Config().bitly_APIKKEY;
private var userName:String = new Config().bitly_USERNAME;
private var apiVersion:String = new Config().bitly_APIVERSION;
public var longURL:String = ''
private var resultReturn:Function;
public function ShortenURL(){}
public function call(URL:String,resultHandler:Function):void
{
resultReturn = resultHandler;
longURL = URL;
var htService:HTTPService = new HTTPService();
htService.method = 'GET';
htService.resultFormat = 'array';
htService.url = 'http://api.bit.ly/shorten';
var params:Object = new Object();
params.longUrl = URL;
params.login = userName;
params.apiKey = apiKey;
params.version = apiVersion;
params.format = 'xml';
htService.addEventListener(ResultEvent.RESULT,resutlHander);
htService.send(params);
}
private function resutlHander(resultEV:ResultEvent):String
{
var shortXML:XML = new XML(resultEV.message.body);
if(shortXML.child("errorCode").toString() == 0)
{
return resultReturn(shortXML.child("results").child('nodeKeyVal').child("shortUrl").toString());
}
else
return resultReturn(longURL);
}
}
}