Introduction
URL shortening services have been around since at least
2002, which was when TinyURL, the first notable shortening service, was launched.
URL shortening services work by taking a long URL as input and generating a shorter URL that, when visited, redirects to the
original, longer URL. URL shortening services are useful for sharing long URLs in limited space, such as in a tweet or PowerPoint
presentation.
There are a variety of free, publicly available URL shortening services, including TinyURL, Bit.ly, and Goo.gl (Google's URL shortener
service), among others. All of these services provide a website where you can create and manage shortened URLs from your browser;
some also offer an API from which you can programmatically create shortened URLs.
This article shows how to use Google's URL Shortener API to create shortened URLs.
Step 1: An Overview of Google's URL Shortener API
The Google URL Shortener API offers programmatic access to goo.gl, which is Google's
URL shortener service. Interfacing with the Google URL Shortener API involves making an HTTP request to https://www.googleapis.com/urlshortener/v1/url and sending
along appropriate parameters. For example, to shorten the URL http://www.dotnetslackers.com, make a POST
request of the following format:
The Google URL Shortener API will then respond with the following:
Here, id reports the shortened URL, while longUrl indicates the URL a user will be
redirected to when the shortened URL is visited. Note that both the data transmitted to and received from the Google URL shortener
service is represented as JSON, which is a lightweight data-exchange format
commonly used in Ajax scenarios.
NOTEAt the time of writing, the Google URL Shortener API is still in Google Labs, meaning it is not a finalized product. Be aware that its functionality or interface may change or
may have changed since this article was authored.
Step 2: Register an API Key
You can use the Google URL Shortener API anonymously, as in the example above. However, Google recommends that you authenticate
when using the API. This is a simple process:
Using an API key grants you a higher number of queries to the URL Shortening API per day - currently, 1,000,000 requests
per day. Moreover, by making authenticated requests you can track your API usage from your Google account.
Calling the Google URL Shortener API from ASP.NET
To generate a short URL from a long one we need to send a properly formatted HTTP request to the Google URL Shortener API. The
HttpWebRequest and HttpWebResponse class's in the
.NET Framework's System.Net namespace contain
all of the functionality we need for issuing the request and reading the response.
The following code starts by creating an
HttpWebRequest object and specifying that the request should be a POST and use a Content-Type
header of application/json. Next, the JSON payload sent in the POST is crafted and then
converted into a byte array so that it can be written to the HttpWebRequest's request stream:
We are now ready to transmit the HTTP request and work with the response. The following code does just that. First,
we call the HttpWebRequest object's GetResponse method, which sends the request and creates a
HttpWebResponse object from which we can examine the response. The response is read into a string and then ASP.NET's
JavaScriptSerializer class is used to deserialize the JSON payload into a ShortenLongUrlResponse
object. (ShortenLongUrlResponse is a class I created that models the data returned by the JSON payload; it has three
string properties: kind, id, and longUrl.)
At this point you can get the shortened URL via the results object's id
property.
The download for this article includes a class named UrlShortener that has a method named
Shorten. Shorten accepts a string as input – the long URL – and returns a
ShortenLongUrlResponse object whose id property specifies the shortened URL. You could use this class
to shorten a URL like so:
Calling the Google URL Shortener API from JavaScript
As we have seen, generating a shortened URL is as simple as sending a properly-formatted HTTP POST request to https://www.googleapis.com/urlshortener/v1/url, and in
ASP.NET this can be accomplished using the HttpWebRequest class. But what if we want to generate a shortened URL from
client-side script? Unfortunately, browsers prohibit cross-domain POST requests from script for security reasons,
meaning we cannot directly call the Google URL Shortener API from JavaScript. Instead, we'll need to use a proxy. Rather
than calling the Google URL Shortener API directly, our script will have to make a request to a web page on our site, which can
then make the call to Google and return the shortened URL.
The demo available for download includes such a proxy. I created a
generic HTTP Handler in the Services folder named Url.ashx. This handler:
- Reads in the querystring parameter
longUrl,
- Sends this value to the Google URL Shortener API, and
- Returns the shortened URL as its output.
For example, visiting www.example.com/Services/Url.ashx?longUrl=http://www.json.org/ returns the response
http://goo.gl/O2WH.
This proxy can then be invoked from JavaScript. The following script shows how to use
jQuery's $.get function to make a request to the proxy and display
the returned shortened URL:
Happy Programming!
Further Reading
About Scott Mitchell
 |
Scott Mitchell, author of eight ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, ...
This author has published 16 articles on DotNetSlackers. View other articles or the complete profile here.
|
You might also be interested in the following related blog posts
Using ASP.NET Routing Without ASP.NET MVC
read more
One Function to Rule All URLs
read more
Upcoming Blog Features Part 2: SEO Improvements
read more
Anonymous Methods vs Threads
read more
Modify Contents of SortedDictionary or Dictionary in foreach
read more
CS Dev Guide: Site Urls
read more
|
|
Please login to rate or to leave a comment.