bitly

[C#] short url 생성(bit.ly)

2014. 2. 13. 13:16
반응형
  • C# bit.ly API 연동 방법

SNS를 연동하다 보면 url에 파라미터가 길게 늘어진 url이 보기 거슬릴때가 있다.  

bit.ly를 활용한 long url을 short url로 make해주는 api가 있는데 매우 효율적인 거 같다. 

다만, 일별 쿼터 제한이 있어 동적으로 사용할 경우 제한 횟수 이상의 요청은 원본 URL로 처리가 됨.

사용한 방식은 클라이언트에서 ajax로 bit.ly api를 호출하고 리턴 받은 short url이 쉐어되도록 개발을 진행.. 우선 개발을 하려면 bit.ly 사이트에서 계정을 발급 받아야 함. 

-share.js 

자바스크립트로 short url 생성 방식

<script>

function facebook_sharer(sharer_title, content_title, sharer_URL) {
    sharer_URL = fn_bitly(sharer_URL);
    var sharer_str = encodeURIComponent(sharer_title.replace(/#/gi, "") + content_title);
    var sharer_url = encodeURIComponent(sharer_URL);
    window.open("http://www.facebook.com/sharer.php?u=" + sharer_url + "&t=" + sharer_str, "facebook_sharer", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=600");
}

function url_sharer(sharer_URL) {
    sharer_URL = fn_bitly(sharer_URL);
    bResult = window.clipboardData.setData("Text", sharer_URL);
    if (bResult) alert('복사되었습니다. 블로그에서 붙여넣기(Ctrl+V)를 이용하세요.');
}

//Short Url Maker
function fn_bitly(longUrl) {
    var shortUrl = "";
    if (longUrl != "") {
        $J.ajax({
            url: '/ajax/bitlyToJson.aspx', //bit.ly api로 다이렉트로 호출해서 short url을 받아도 무방.
            type: 'POST',
            dataType: 'json',
            data: {
                longUrl: longUrl
            },
            timeout: 1000,
            async: false,
            error: function(xhr) {
                //alert('xhr (' + xhr.status + ':'+ xhr.statusText + ':' + xhr.responseText + ')');
            },
            success: function(response) {
                _jsonObject = response.data;
                shortUrl = _jsonObject.url;
            }
        });
        if (shortUrl == "") shortUrl = longUrl;
    }
    return shortUrl;
}

</script>
-bitlyToJson.cs

c# 에서 short url 생성 방식
 

/******************************************************************************
 *  제  목 : bitlyToJson
 *  작성자 : 이종필
 *  작성일 : 2012-11-08
 *  설  명 : Long Url -> Short Url로 Json 리턴
 ******************************************************************************/

#region shortUrl 생성
    ///    /// https://bitly.com/ 사이트에서 발급
    /// format : json
    /// apiKey : R_b7b8ddaf4734eba87237d5ad*******
    /// login : leejon****
    ///    
    private void MakeShorURL(string longurl)
    {
        StringBuilder sb = new StringBuilder();

        //base
        sb.Append(@"http://api.bit.ly/v3/shorten?login=leejon****l&apiKey=R_b7b8ddaf4734eba87237d5ad5*****&format=json&longUrl=");
        //server page
        sb.Append(Server.UrlEncode(longurl));

        // Make Short URL
        WebClient client = new WebClient();
        string shorturl = client.DownloadString(new Uri(sb.ToString()));

        Response.Write(shorturl);
    }

#endregion
결과는 아래와 같이 JSON, XML 데이타로 리턴된다. 
호출하는 데이타 format (json, xml) 파라미터로 제어 가능.
 
-JSON
 
{ "status_code": 200, "status_txt": "OK", "data": { "long_url": "http:\/\/www.naver.com\/", "url": "http:\/\/bit.ly\/YNBfGD", "hash": "YNBfGD", "global_hash": "md7fw", "new_hash": 0 } } 
 
-XML
<response>
 <status_code>200</status_code>
 <status_txt>OK</status_txt>
 <data>
  <url>http://bit.ly/YNBfGD</url>
  <hash>YNBfGD</hash>
  <global_hash>md7fw</global_hash>
  <long_url>http://www.naver.com/</long_url>
  <new_hash>0</new_hash>
 </data>
</response>

 

반응형

+ Recent posts

반응형