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

Pin on pinterest Plus on Googleplus Post on LinkedIn

Comments

Comment by Kevin Becker

Dude, you're my hero with this code. But I have a question, how can I get this to use my Google Apps account instead of the standard goo.gl URL? I have everything setup on the Google side.

I think I have to add something called OAuth? Any help would be greatly appreciated!

Kevin Becker
Comment by Stephen

Hey man perfect code! exactly what I needed.

How can I use this to access the goo.gl analytics?

Stephen
Comment by Stephen

Great post! This and your other post on goo.gl API were so helpful!

How could you use this, with the API key, to access the analytics for a particular goo.gl url?

Stephen
Comment by mewtwo8

Thank you dude, very usefull!!!

mewtwo8
Comment by Marlin May

Thank you!
You, sir, are a lifesaver!
Send me your postal address and I'll send you a six pack of the finest Massachusetts has to offer.

Marlin May
Comment by Kailash

Hello Sir,
Thank you for posting this nice post,
i m working on .NET 4.0 i want to use your code in my website
please suggest me how can i use this code?

Thank You

Kailash