Google Short Url in asp.net c#

Many times we have some very long URL to show or send someone, we use short URL technique (URL shortening is a technique on the World Wide Web in which a Uniform Resource Locator may be made substantially shorter and still direct to the required page. This is achieved by using a redirect which links to the web page that has a long URL.)  to short the URL.


Here we use Google short URL technique for short the URL in asp.net c#

Step1. First, you have your own API key so you can GET API KEY


Code Behind (C#):-


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;

public partial class short_url : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Shortenurl();
        }
    }


    string key = "AIzaSyCTMnlo3HBIM5l_yPeyTaEsVBjAnqCXtfA";

    public void Shortenurl()
    {
        string url = "https://www.neerajcodesolutions.com/2018/10/google-short-url-in-aspnet-c.html";
        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;
                    }
                }
            }

            Response.Write(shorturl);
        }
        catch (Exception ex)
        {
           
            Response.Write(ex.Message);
            Response.Write(ex.StackTrace);
        }

    }

}



Google Short Url in asp.net c# Google Short Url in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 9:18:00 PM Rating: 5

No comments:

Powered by Blogger.