Thursday, May 26, 2011

URL shortener in .net using bit.ly API

It’s simple to generate shorten url based on long url using bit.ly API.

For this we need to have account with http://bit.ly/a/sign_up which is free. After sign up completed, you will be provided with an API key http://bit.ly/a/your_api_key

This API key can be used to access the API. Below is the code for API class in c#

public static class BitlyApi
{
private const string apiKey = "[add api key here]"
;
private const string login = "[add login name here]"
;

public static BitlyResults ShortenUrl(string
longUrl)
{
var url =
string.Format("http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}"
,
HttpUtility.UrlEncode(longUrl), login, apiKey);
var resultXml = XDocument.Load(url);
var x = (from result
in resultXml.Descendants("nodeKeyVal"
)
select
new
BitlyResults
{
UserHash = result.Element(
"userHash"
).Value,
ShortUrl = result.Element(
"shortUrl"
).Value
}
);
return
x.Single();
}
}

public class
BitlyResults
{
public string
UserHash { get; set; }

public string ShortUrl { get; set; }
}


Now, we can generate short url as below:


string strShortUrl = BitlyApi.ShortenUrl(“<long url>).ShortUrl;


Happy Coding…

1 comment:

  1. I know improvement's still in advance, however at whatever point you get around to it my supplication is to make a point to graphically speak to the children as fitting. I.e. little and off the beaten path. As of now, they occupy and overpower as they take up such a great amount of room on the page. url shortener google

    ReplyDelete