Shorten your URL with Goo.gl in Asp.Net Using C#


Link For the API

Step 1

Enable the shotren url API here

Step 2

Get the API Key

Step 3

Add the following name spaces

using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

Public class GoogleShortnerApi
{
private const string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";

public static string Shorten(string url)
{
string post = "{\"longUrl\": \"" + url + "\"}";
string shortUrl = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);

try
{
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");

using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
shortUrl = Regex.Match(json, @"""id"": ?""(?.+)""").Groups["id"].Value;
}
}
}
}

return shortUrl;
}
}

Advertisements

Shorten your URL with Bit.ly in Asp.Net Using C#


The code is also very simple. I didn’t add all the extra options that the API makes available and just wrote enough for me to shorten a URL. Here it is:

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; }
}

The API is pretty well documented at http://code.google.com/p/bitly-api/wiki/ApiDocumentation