8 Comments
  •   Posted in: 
  • C#

Google announced this API yesterday on their blog.

There are no examples for Asp.Net C# so I made this class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace shop.BLL.Utility
{
    public class GoogleUrlShortnerApi
    {
        private const string key = "xxxxxx mykey xxxxxxx";

        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"": ?""(?<id>.+)""").Groups["id"].Value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // if Google's URL Shortner is down...
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            return shortUrl;
        }
    }
}

You can obtain a free key from the API Console which is recommended so that you can do 1.000.000 queries a day!

I really recommend using the goo.gl for shortening URL’s for SEO purposes. Google can see the long URL

(by the way, you can retrieve it yourself too if you like, the documentation is there and with this code sample, you should be ok)

Good luck shortening!

kick it on DotNetKicks.com Shout it

Post on LinkedIn