C# - Shorten a URL with bit.ly shortening service

By , 9/17/2012
(1 ratings)
This function allows you to shorten a URL using the bit.ly shortening service. Using the API requires credentials you can obtain after registering free at http://bit.ly/account/your_api_key.

The parameter AddHistory determines whether the shortened URL should be saved in the account history of your bit.ly account or not.

As a result this function returns a Uri that contains the shortened URL. If an error occurs, the original Uri is returned to avoid cumbersome error handling.

Author: Gordon Breuer, translation by Michael List
Translate to VB
/// <summary>Shortens the given URL using bit.ly</summary>
/// <param name="longUri">Long URL to be shortened</param>
/// <param name="login">Login name of your bit.ly account (http://bit.ly/account/your_api_key).</param>
/// <param name="apiKey">API key of your bit.ly account (http://bit.ly/account/your_api_key).</param>
/// <param name="addHistory">If you set this parameter to <c>true</c>, the shortened URLs are saved in the account history of the user.</param>
/// <returns>A shortened bit.ly Uri or the original Uri if an error occured</returns>
private Uri ShortenUri(Uri longUri, string login, string apiKey, bool addHistory) {
  const string bitlyUrl = @"http://api.bit.ly/shorten?longUrl={0}&apiKey={1}&login={2}&version=2.0.1&format=json&history={3}";
  var request = WebRequest.Create(string.Format(bitlyUrl, longUri, apiKey, login, addHistory ? "1" : "0"));
  var response = (HttpWebResponse)request.GetResponse();
  string bitlyResponse;
  using (var reader = new StreamReader(response.GetResponseStream())) {
    bitlyResponse = reader.ReadToEnd();
  }
  response.Close();
  if (!string.IsNullOrEmpty(bitlyResponse)) {
    const RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
    const string rx = "\"shortUrl\":\\ \"(?<short>.*?)\"";
    Regex reg = new Regex(rx, options);
    string tmp = reg.Match(bitlyResponse).Groups["short"].Value;
    return string.IsNullOrEmpty(tmp) ? longUri : new Uri(tmp);
  }
  return longUri;
}
Tagged with shortener, shorturl, tinyurl, bitly.

Comments

 

Log in, to comment!