Using Google API – URL shortener C#

This post aim to walkthrough the steps required to set up Google URL Shortener in C#
To get started, visit Google API Console
Head over to Services and toggle URL Shortener API to ON.
Once URL Shortner API is turned on, retrieve your API Key from API Access.

The full documentation on the URL Shortner API is available here.

The api returns a json and a regex expression may used to extract the shortened URL from the return.

private const string key = "xxxxxInsertGoogleAPIKeyHerexxxxxxxxxx";
public string urlShorter(string url)
{
            string finalURL = "";
            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();
                            finalURL = Regex.Match(json, @"""id"": ?""(?.+)""").Groups["id"].Value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // if Google's URL Shortener is down...
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            return finalURL;
}
Advertisements
This entry was posted in Google and tagged , , , . Bookmark the permalink.

13 Responses to Using Google API – URL shortener C#

  1. Anonymous says:

    return finalURL?

    Like

    • LZH says:

      Thanks for pointing it out. Made the amendment, it should be finalURL = Regex.Match(json, @”””id””: ?””(?.+)”””).Groups[“id”].Value;

      Like

  2. Hi to every one, it’s actually a fastidious for me to visit this
    website, it contains helpful Information.

    Like

  3. Very good information. Lucky me I discovered your blog by chance
    (stumbleupon). I have saved it for later!

    Like

  4. Max says:

    Pretty component of content. I just stumbled upon your site and in accession capital to
    assert that I get in fact enjoyed account your blog posts.
    Any way I will be subscribing in your augment or even I achievement
    you get admission to consistently rapidly.

    Like

  5. We’re a group of volunteers and starting a
    new scheme in our community. Your site offered us with
    valuable information to work on. You’ve done a formidable job and our entire community will be grateful to you.

    Like

  6. Hi to all, the contents present at this website are actually awesome for people knowledge, well,
    keep up the good work fellows.

    Like

  7. HLA says:

    I got the error from Google.
    “System.Net.WebException: The remote server returned an error: (403)
    Forbidden”

    How should i solve this issue?

    Thanks.

    Like

  8. It is in reality a great and helpful piece of information.
    I am glad that you simply shared this helpful info with
    us. Please keep us up to date like this. Thank you for sharing.

    Like

  9. I think this is among the such a lot vital information for me.
    And i’m happy reading your article. But should commentary on few common issues, The
    site taste is great, the articles is actually excellent :
    D. Just right job, cheers

    Like

  10. You actually make it appear so easy together with your presentation but
    I in finding this matter to be actually one thing which I believe I’d never understand.
    It kind of feels too complex and very large for me.
    I am taking a look ahead to your next put up, I’ll attempt to get the dangle of
    it!

    Like

  11. Piece of writing writing is also a excitement, if you be familiar with
    after that you can write or else it is difficult to write.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s