[C#]Google Url Shortening

[C#]Google Url Shortening

Google Url Shortening是Google所提供的短網址服務,能將長網址縮短成短網址,或將縮短後的短網址還原成長網址,另外它也提供了分析資訊與使用者歷史記錄等功能。

 

使用時有的地方像是縮短網址那邊會用到API Key,需先連至APIs Console將你要的服務開啟。

image

 

再至API Access取得API Key。

image

 

在縮短網址那邊,處理上是向https://www.googleapis.com/urlshortener/v1/url發送APIKey與Post訊息,ContentType為application/json,其Post內容為{"longUrl": "[長網址]"}。


Content-Type: application/json

{"longUrl": "http://www.google.com/"}

 

回傳的內容會像下面這樣,有kind、 id、與longUrl,我們多半只需要取得id即可。


 "kind": "urlshortener#url",
 "id": "http://goo.gl/fbsS",
 "longUrl": "http://www.google.com/"
}

 

以C#實做此概念程式如下;


        {
            if (String.IsNullOrEmpty(url))
                throw new ArgumentNullException("url");

            if (m_APIKey.Length == 0)
                throw new Exception("APIKey not set!");

            const string POST_PATTERN = @"{{""longUrl"": ""{0}""}}";
            const string MATCH_PATTERN = @"""id"": ?""(?<id>.+)""";

            var post = string.Format(POST_PATTERN, url);
            var request = (HttpWebRequest)WebRequest.Create(string.Format(URL_SHORTENER_URL_PATTERN, m_APIKey));
            
            request.Method = "POST";
            request.ContentLength = post.Length;
            request.ContentType = "application/json";
            request.Headers.Add("Cache-Control", "no-cache");

            using (Stream requestStream = request.GetRequestStream())
            {
                var buffer = Encoding.ASCII.GetBytes(post);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            using (var responseStream = request.GetResponse().GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    return Regex.Match(sr.ReadToEnd(), MATCH_PATTERN).Groups["id"].Value;
                }
            }
            return string.Empty;
        }

 

而在展開短網址方面就更為簡單了,展開的動作只需在https://www.googleapis.com/urlshortener/v1/url後面加上shortUrl的參數,將短網址帶入。

 

即會回傳像下面這樣的資訊,我們需要的展開後網址即回傳的longUrl。


 "kind": "urlshortener#url",
 "id": "http://goo.gl/fbsS",
 "longUrl": "http://www.google.com/",
 "status": "OK"
}

 

以C#實做此概念的話程式如下:


        {
            HttpWebRequest request = (WebRequest.Create(url)) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }

        public String Expand(string url)
        {
            const string MATCH_PATTERN = @"""longUrl"": ?""(?<longUrl>.+)""";

            var expandUrl = string.Format(EXPAND_URL_PATTERN, url);
            var response = GetHTMLSourceCode(expandUrl);

            return Regex.Match(response, MATCH_PATTERN).Groups["longUrl"].Value;
        }

 

這邊有整理個較為完整的Class,有需要的直接取用。


using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace LevelUp.Google
{
    public class GoogleUrlShortener
    {
        #region Const
        const String BASE_API_URL = @"https://www.googleapis.com/urlshortener/v1/url";
        const String SHORTENER_URL_PATTERN = BASE_API_URL + @"?key={0}";
        const String EXPAND_URL_PATTERN =  BASE_API_URL + @"?shortUrl={0}";
        #endregion

        #region Var
        private String _apiKey;
        #endregion

        #region Private Property
        private String m_APIKey 
        {
            get
            {
                if (_apiKey == null)
                    return string.Empty;
                return _apiKey;
            }
            set
            {
                _apiKey = value;
            }
        }
        #endregion

        #region Constructor
        public GoogleUrlShortener(string apiKey)
        {
            if (string.IsNullOrEmpty(apiKey))
                throw new ArgumentNullException("apiKey");

            this.m_APIKey = apiKey;
        }
        #endregion

        #region Private Method
        private string GetHTMLSourceCode(string url)
        {
            HttpWebRequest request = (WebRequest.Create(url)) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
        #endregion

        #region Public Method
        public string Shorten(string url)
        {
            if (String.IsNullOrEmpty(url))
                throw new ArgumentNullException("url");

            if (m_APIKey.Length == 0)
                throw new Exception("APIKey not set!");

            const string POST_PATTERN = @"{{""longUrl"": ""{0}""}}";
            const string MATCH_PATTERN = @"""id"": ?""(?<id>.+)""";

            var post = string.Format(POST_PATTERN, url);
            var request = (HttpWebRequest)WebRequest.Create(string.Format(SHORTENER_URL_PATTERN, m_APIKey));
            
            request.Method = "POST";
            request.ContentLength = post.Length;
            request.ContentType = "application/json";
            request.Headers.Add("Cache-Control", "no-cache");

            using (Stream requestStream = request.GetRequestStream())
            {
                var buffer = Encoding.ASCII.GetBytes(post);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            using (var responseStream = request.GetResponse().GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    return Regex.Match(sr.ReadToEnd(), MATCH_PATTERN).Groups["id"].Value;
                }
            }
            return string.Empty;
        }

        public String Expand(string url)
        {
            const string MATCH_PATTERN = @"""longUrl"": ?""(?<longUrl>.+)""";

            var expandUrl = string.Format(EXPAND_URL_PATTERN, url);
            var response = GetHTMLSourceCode(expandUrl);

            return Regex.Match(response, MATCH_PATTERN).Groups["longUrl"].Value;
        }
        #endregion
    }
}

 

Link