(redirected from Main.ShorteningLinksWithBitly)
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
- Bit.ly API Documentation
- Bit.ly API keys - must be logged in first -- once logged in, can select from the
Toolsmenu.
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:
- $longurl='http://www.example.com';
- $bitlylogin='BITLY_LOGIN'; // your login name here
- $bitlyapikey='BITLY_API_KEY'; // your api key here
- $shorturl = file_as_content("http://api.bit.ly/v3/shorten?login=$bitlylogin&apikey=$bitlyapikey&longUrl=' . urlescape($longurl) . '&format=txt');
- if (!empty($shorturl) && strpos($shorturl,'<html>') === false) {
- # procede with the shortened url
- }
- use strict;
- use LWP::UserAgent;
- use URI::Escape;
- my $longurl='http://www.example.com';
- my $bitlylogin='BITLY_USER';
- my $bitlyapikey='BITLY_API_KEY';
- my $ua = LWP::UserAgent->new;
- $ua->timeout(10);
- $ua->user_agent('Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0');
- my $response = $ua->get('http://api.bit.ly/v3/shorten?login=$bitlylogin&apikey=$bitlyapikey&longUrl=' . uriescape($longurl) . '&format=txt');
- die $response->status_line if (!$response->is_success);
- 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?