अजपा योग आणि शांभवी मुद्रा ध्यान : श्वास, मंत्र, मुद्रा आणि ध्यान यांच्या सहाय्याने मनःशांती, एकाग्रता, चक्र संतुलन आणि कुंडलिनी जागृती. अधिक माहिती आणि आगामी तारखांसाठी येथे जा.

Untitled 1

Generating Short URLs using Google URL Shortener API

At times URLs that you wish to share with others are too long to be shared in their original form. Such long URLs can affect the readability and flow of your message. Additionally, they are unsuitable to use with applications such as Twitter because of their length. Many websites, therefore, allow you to create a shorter version of a URL which gets expanded to the full original URL when accessed. Google provides such a facility through their goo.gl website. You can go to goo.gl website and manually generate a short version of a URL by manually entering it. The following figure shows the goo.gl website:

Though this manual approach of generating short URLs works well for the known URLs, it's unsuitable in situations where you need to generate a short URL at runtime. Consider, for example, that you are developing your own photo album website. For the sake of SEO and other reasons you have created long URLs that include the date stamp of the photo and its title. Now, if you want the end users to share URLs to their photos with their friends via email or social networking websites you can't expect them to go to Google url shortener to generate a short version of their photo URLs. In such cases it would be better to integrate the functionality of generating shorter URLs in your web application itself. Luckily, Google url shortener exposes an API that can be used to accomplish this job.

To use the Google url shortener API you need an API key that is specific to your Google account. To get this API key go to Google API console, active Google URL Shortener API service and get your key from the API Access option.

Once you get the API key you are ready to use it in any ASP.NET project.

To illustrate the generation of short URLs using Google URL Shortener API we will develop an ASP.NET MVC application. So, begin by creating a new ASP.NET MVC 4 project in Visual Studio 2012.

Once created, add a new controller to the project and name it as HomeController. Inside HomeController add a new action method as shown below:

public JsonResult GetShortURL(string longUrl)
    WebRequest request = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY_HERE");
    request.Method = "POST";
    request.ContentType = "application/json";
    string requestData = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);
    byte[] requestRawData = Encoding.ASCII.GetBytes(requestData);
    request.ContentLength = requestRawData.Length;
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(requestRawData, 0, requestRawData.Length);

    WebResponse response = request.GetResponse();
    StreamReader responseReader = new StreamReader(response.GetResponseStream());
    string responseData = responseReader.ReadToEnd();

    var deserializer = new JavaScriptSerializer();
    var results = deserializer.Deserialize<GoogleResponse>(responseData);
    return Json(results.Id);

The GetShortURL() action method returns JsonResult because you will calling it through the client side jQuery code. It accepts longUrl as a parameter that indicates the URL you wish to shorten. Inside it creates an instance of WebRequest object using the static Create() method. Notice the parameter passed to the Create() method. This the Google URL Shortener service end point. Also note that you should pass your API key in the key query string parameter.

The method property of the WebRequest object is set to POST indicating that you will be issuing an HTTP POST request. The ContentType property indicates the type of content sent during the POST request. In this case it is application/json because the Google URL Shortener API expects the long URL encapsulated in a JSON object as shown in the string.Format() call on the next line.

To send this JSON object you first use  GetRequestStream() method that returns a Stream object for the request. Then you use the write() method to write a byte array representation of the JSON data. Finally, request stream is closed.

To read the response sent back by the Google URL Shortener service you use GetResponse() method. The actual response is read using a StreamReader object. The response sent by the service is in the form of a JSON object. To convert this JSON object into a .NET object you first need to define a class that mimics the structure of the JSON object. In our example the GoogleResponse class does this job and is shown below:

public class GoogleResponse
    public string Kind { get; set; }
    public string Id { get; set; }
    public string LongUrl { get; set; }

As you can see the GoogleResponse class contains three public string properties viz. Kind, Id and LongUrl. The Id property will contain the short version of the specified LongUrl.

The JavaScriptSerializer class used in the GetShortURL() action method deserializes the JSON response into a .NET object of type GoogleResponse. Once deserialized you can return the Id property of the GoogleResponse object to the caller. Notice the use of Json() method that converts an object into its JSON equivalent. You could have directly sent the JSON response to the caller but in this case you wish to return only the short URL string to the caller.

Next, add Index view to the project and modify its HTML markup as shown below:

<span>Enter Long URL :</span>
<br />
<br />
<input type="text" id="text1" size="60" />
<br /><br />
<input type="button" id="button1" value="Get Short URL"/>
<br /><br />
<input type="text" id="text2" readonly="readonly" size="60" />

The view consists of two textboxes and a button. The first textbox accepts the long URL whereas the second textbox displays the short URL returned from the GetShortURL() action method. That's why it is read only.

Now, add the following jQuery code in a <script> block:

$(document).ready(function () {
    $("#button1").click(function () {
            type: "POST",
            url: "/home/GetShortURL",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: '{ "longUrl" : "' + $("#text1").val() + '" }',
            success: function (results) {
            error: function (err) {
                alert(err.status + " - " + err.statusText);

The ready() function contains code that represents the click event handler of the "Get Short URL" button. The click event handler uses jQuery $.ajax() to make a POST request to the GetShortURL() action method you created earlier. The type and url parameters indicate these two pieces of request. The data is passed as a JSON object and comprises of the longUrl grabbed from the first textbox. The success parameter receives the short version of the URL and the same is displayed to the end user in the second textbox.

That's it! Run the application, enter some long URL and click on the "Get Short URL" button. The second textbox should show the http://goo.gl URL for the long URL. Verify that the short URL takes you to the long URL by entering in a new browser window.




Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 04 March 2013