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.

21 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. Thanks to my father who stated to me concerning this webpage, this web
    site is really awesome.

    Like

  10. Sam says:

    It works for me but the shorten links aren’t appearing in the Analytics google shorten page to track the links if they are being clicked or not .. any help.

    Like

  11. pregunton says:

    Google Transits URL Shortener Service To Firebase Dynamic Links
    https://www.c-sharpcorner.com/news/google-transits-url-shortener-service-to-firebase-dynamic-links

    How use it in C# ?

    Like

  12. Matilda says:

    I conceive this site holds very superb written subject material posts.

    Like

  13. Nice post. I used to be checking continuously this weblog and
    I am inspired! Very useful info particularly the last phase
    🙂 I take care of such information a lot. I used to be seeking
    this certain info for a very long time. Thank you and good luck.

    Like

  14. I like this web blog so much, saved to favorites.

    Like

  15. Ripoplex says:

    I am always thought about this, regards for posting.

    Like

  16. Some truly terrific work on behalf of the owner
    of this internet site, absolutely outstanding subject matter.

    Like

  17. An impressive share! I’ve just forwarded this onto a coworker who was conducting a little research on this.

    And he actually ordered me breakfast because I discovered it for
    him… lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to talk about this topic here on your website.

    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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s