Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#
Tip/Trick

Creating A Google Url Shortner

Rate me:
Please Sign up or sign in to vote.
1.92/5 (3 votes)
26 Jun 2011CPOL 21.8K   4   5
This is a simple way to shorten a Url with google. This will produce a link equivalent to a bit.ly, scut.ly, shorturl, and tinyurl. the original source which has a few more methods included for expanding the short url back to the original url. youc can find this source at http://www.jarloo.com/code/api-code/google-url-shortening/.
C#
// Code Provided by  http://jarloo.com/code/api-code/google-url-shortening/
namespace WindowsFormsApplication1
{
    using System;
    using System.Windows.Forms;    
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Net;

    public partial class Form1 : Form
    {
        private System.Windows.Forms.TextBox InputBox;
        private System.Windows.Forms.TextBox OutputBox;
        private System.Windows.Forms.Button BtnShorten;
        private System.Windows.Forms.Label InputLabel;
        private System.Windows.Forms.Label OutputLabel;

        public Form1()
        {
            InitializeComponent();
        }

        public class GoogleUrlShortner
        {
            public static GoogleUrlReply Shorten(string longUrl)
            {
                string data = "{\"longUrl\":\"" + longUrl + "\"}";
                string gUrl = "https://www.googleapis.com/urlshortener/v1/url";

                string response = Post(gUrl, data);
                return FromJSON<GoogleUrlReply>(response);
            }
           
            private static string Post(string url, string data)
            {
                WebRequest request = WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                byte[] byteData = Encoding.UTF8.GetBytes(data);

                request.ContentLength = byteData.Length;

                using (Stream s = request.GetRequestStream())
                {
                    s.Write(byteData, 0, byteData.Length);
                    s.Close();
                }

                string replyData;

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            replyData = reader.ReadToEnd();
                        }
                    }
                }

                return replyData;
            }

            private static T FromJSON<T>(string input)
            {
                MemoryStream stream = new MemoryStream();

                try
                {
                    DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
                    stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
                    T obj = (T)jsSerializer.ReadObject(stream);

                    return obj;
                }
                finally
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }

        public class GoogleUrlReply
        {
            public string id { get; set; }
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.InputBox = new System.Windows.Forms.TextBox();
            this.OutputBox = new System.Windows.Forms.TextBox();
            this.BtnShorten = new System.Windows.Forms.Button();
            this.InputLabel = new System.Windows.Forms.Label();
            this.OutputLabel = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.InputBox.Location = new System.Drawing.Point(83, 12);
            this.InputBox.Name = "textBox1";
            this.InputBox.Size = new System.Drawing.Size(463, 20);
            this.InputBox.TabIndex = 0;
            // 
            // textBox2
            // 
            this.OutputBox.Location = new System.Drawing.Point(83, 38);
            this.OutputBox.Name = "textBox2";
            this.OutputBox.ReadOnly = true;
            this.OutputBox.Size = new System.Drawing.Size(463, 20);
            this.OutputBox.TabIndex = 1;
            // 
            // BtnShorten
            // 
            this.BtnShorten.Location = new System.Drawing.Point(83, 64);
            this.BtnShorten.Name = "BtnShorten";
            this.BtnShorten.Size = new System.Drawing.Size(75, 23);
            this.BtnShorten.TabIndex = 2;
            this.BtnShorten.Text = "Shorten";
            this.BtnShorten.UseVisualStyleBackColor = true;
            this.BtnShorten.Click += new System.EventHandler(this.BtnShorten_Click);
            // 
            // label1
            // 
            this.InputLabel.AutoSize = true;
            this.InputLabel.Location = new System.Drawing.Point(12, 19);
            this.InputLabel.Name = "label1";
            this.InputLabel.Size = new System.Drawing.Size(51, 13);
            this.InputLabel.TabIndex = 3;
            this.InputLabel.Text = "Enter Url ";
            // 
            // label2
            // 
            this.OutputLabel.AutoSize = true;
            this.OutputLabel.Location = new System.Drawing.Point(12, 41);
            this.OutputLabel.Name = "label2";
            this.OutputLabel.Size = new System.Drawing.Size(39, 13);
            this.OutputLabel.TabIndex = 4;
            this.OutputLabel.Text = "Output";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(558, 99);
            this.Controls.Add(this.OutputLabel);
            this.Controls.Add(this.InputLabel);
            this.Controls.Add(this.BtnShorten);
            this.Controls.Add(this.OutputBox);
            this.Controls.Add(this.InputBox);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {            
            Application.Run(new Form1());
        }

        private void BtnShorten_Click(object sender, EventArgs e)
        {
            GoogleUrlReply reply = GoogleUrlShortner.Shorten(InputBox.Text);
            OutputBox.Text = reply.id;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
GeneralReason for my vote of 2 slightly better. A few examples woul... Pin
Luc Pattyn26-Jun-11 13:11
sitebuilderLuc Pattyn26-Jun-11 13:11 
GeneralReason for my vote of 1 I agree with Luc. It needs some expl... Pin
Dr.Walt Fair, PE25-Jun-11 15:44
professionalDr.Walt Fair, PE25-Jun-11 15:44 
GeneralRe: updated Pin
charles henington26-Jun-11 12:28
charles henington26-Jun-11 12:28 
GeneralReason for my vote of 1 No description, no explanation, no t... Pin
Luc Pattyn25-Jun-11 13:20
sitebuilderLuc Pattyn25-Jun-11 13:20 
GeneralRe: updated Pin
charles henington26-Jun-11 12:27
charles henington26-Jun-11 12:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.