재우니의 블로그


asp.net 으로 google URL Shortener 짧은 주소 url 구현하기


nuget 을 통해 Google.Apis.Urlshortener.v1 검색해서 다운로드 받으시고, 아래 소스로 사용해 보시면 됩니다.


https://console.developers.google.com


구글 개발 콘솔 사이트 가서, 프로젝트 구성하고, 라이브러리 가서, "URL Shortener API  사용"을 선택하시면 됩니다.

그리고 나서 "사용자인증정보" 메뉴에서 "서버키"를 하나 만들어서 아래 apikey 에 값을 넣습니다.


펌 : https://raw.githubusercontent.com/google/google-api-dotnet-client-samples/master/UrlShortener.ASP.NET/Default.aspx.cs


/*
Copyright 2011 Google Inc

Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Text.RegularExpressions;

using Google;
using Google.Apis.Services;
using Google.Apis.Urlshortener.v1;
using Google.Apis.Urlshortener.v1.Data;

namespace UrlShortener.ASP.NET
{
    /// <summary>
    /// ASP.NET UrlShortener Sample. This sample makes use of ASP.NET and the UrlShortener API to demonstrate how to do
    /// make unauthenticated requests to an API.
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {
        private static UrlshortenerService service;

        protected void Page_Load(object sender, EventArgs e)
        {
            // If we did not construct the service so far, do it now.
            if (service == null)
            {
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                // You can enter your developer key for services requiring a developer key.
                initializer.ApiKey = "<Insert Developer Key here>";
                service = new UrlshortenerService(initializer);

            }
        }

        protected void input_TextChanged(object sender, EventArgs e)
        {
            // Change the text of the button according to the content.
            action.Text = IsShortUrl(input.Text) ? "Expand" : "Shorten";
        }

        protected void action_Click(object sender, EventArgs e)
        {
            string url = input.Text;
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            // Execute methods on the UrlShortener service based upon the type of the URL provided.
            try
            {
                string resultURL;
                if (IsShortUrl(url))
                {
                    // Expand the URL by using a Url.Get(..) request.
                    Url result = service.Url.Get(url).Execute();
                    resultURL = result.LongUrl;
                }
                else
                {
                    // Shorten the URL by inserting a new Url.
                    Url toInsert = new Url { LongUrl = url };
                    toInsert = service.Url.Insert(toInsert).Execute();
                    resultURL = toInsert.Id;
                }
                output.Text = string.Format("<a href=\"{0}\">{0}</a>", resultURL);
            }
            catch (GoogleApiException ex)
            {
                var str = ex.ToString();
                str = str.Replace(Environment.NewLine, Environment.NewLine + "<br/>");
                str = str.Replace("  ", " &nbsp;");
                output.Text = string.Format("<font color=\"red\">{0}</font>", str);
            }
        }

        private static readonly Regex ShortUrlRegex =
                    new Regex("^http[s]?://goo.gl/", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        private static bool IsShortUrl(string url)
        {
            return ShortUrlRegex.IsMatch(url);
        }
    }
}