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…