Greytree

TamWiki

For a mouse who is a packrat

Technology » Shortening Links With Bitly
using the url shortening service programmatically

Summary:this is what goes at the top of the site

(redirected from Main.ShorteningLinksWithBitly)

Next: SSH >>

<< Prev: Rsync Backups

Up: ^Tools^

On this page... (hide)

The URL-shortening service bit.ly has an API that let's you get a short URL programmatically, thus making it really useful for including in web apps.

Links

How To?

The basic call to the bit.ly API is as follows:

 http://api.bit.ly/v3/shorten?login=BITLYLOGIN&apikey=BITLYAPIKEY&longUrl=ESCAPEDURL&format=(txt|json|xml)

The format= parameter determines how bit.ly will return the shortened URL.

  • txt - a bare URL without any markup, e.g. http://bit.ly/code
  • json - returned in a json-compatible format
  • xml - returned as xml

If bit.ly has errors in generating the URL, it returns a short HTML page. If it doesn't recognize the login or key, it returns nothing. Thus you should check for these on return:

PHP example
  1. $longurl='http://www.example.com';
  2. $bitlylogin='BITLY_LOGIN'; // your login name here
  3. $bitlyapikey='BITLY_API_KEY'; // your api key here
  4. $shorturl = file_as_content("http://api.bit.ly/v3/shorten?login=$bitlylogin&apikey=$bitlyapikey&longUrl=' . urlescape($longurl) . '&format=txt');
  5. if (!empty($shorturl) && strpos($shorturl,'<html>') === false) {
  6.   # procede with the shortened url
  7. }
Perl example
  1. use strict;
  2. use LWP::UserAgent;
  3. use URI::Escape;
  4.  
  5. my $longurl='http://www.example.com';
  6. my $bitlylogin='BITLY_USER';
  7. my $bitlyapikey='BITLY_API_KEY';
  8.  
  9. my $ua = LWP::UserAgent->new;
  10. $ua->timeout(10);
  11. $ua->user_agent('Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0');
  12. my $response = $ua->get('http://api.bit.ly/v3/shorten?login=$bitlylogin&apikey=$bitlyapikey&longUrl=' . uriescape($longurl) . '&format=txt');
  13. die $response->status_line if (!$response->is_success);
  14. print $response->decoded_content;


Tags: Categories: HowTos

Recent Changes | Printable View | Page History | Edit Page
Page last modified on April 17, 2012, at 08:59 PM by ImportText?