트위터, 페이스북과 같은 SNS가 유행하면서 제한된 문자수를 극복하기 위해 또는 너무 길어서 지지분해 보이는 URL을 짧고 간결하게 표시하기 위한 짧은 URL(Short URL Service) 서비스가 필수가 되었습니다. 

tinyurl.com, shorl.com, goo.gl 등 짧은 URL 서비스를 제공하는 사이트가 많은데요. 그중에 많이들 쓰시는 bit.ly 서비스를 프로그래밍을 통해서 짧은 URL을 만들어 쓸 수 있습니다. OAuth, REST API, QR Code 등 몇 가지 방법을 제공하는데 그중에 가장 간단한 REST API 를 통해서 짧은 URL을 만드는 방법을 알아보겠습니다. 

준비
1) 먼저 bit.ly 사이트에 접속하셔서 계정을 만듭니다. http://bit.ly/a/sign_up
2) API Key를 받습니다.  http://bit.ly/a/your_api_key 
3) API 문서는 여기에 있어요. http://code.google.com/p/bitly-api/wiki/ApiDocumentation

요청/응답
1) HTTP GET으로 요청 URL을 만듭니다. 

요청 URL : http://api.bit.ly/v3/shorten 

http://api.bit.ly/v3/shorten?login=아이디&apiKey=API_KEY
&longUrl=긴URL&format=txt

요청 파라미터
 format  json, xml, txt를 지원합니다. 
 longUrl  원본 URL. 긴 URL (URL 인코딩 필요)
 domain   (옵션) bit.ly (기본값)를 쓸것인지? j.mp를 쓸 것인지?
 x_login  (옵션) 계정 만들때 사용한 아이디
 x_apiKey  (옵션) 준비단계에서 받은 API Key 

예)
http://api.bit.ly/v3/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07
&longUrl=http%3A%2F%2Fbetaworks.com%2F&format=json

예제 요청URL처럼 longUrl은 URL인코딩이 필요합니다. 

인증도 없고 HTTP GET으로 요청을 하니 매우 간단하네요. 

2) 응답받기

응답은 3가지 포멧으로 가능합니다. json (jsonp), xml, txt. 필요에 따라서 선택을 하면됩니다. 

JSON응답
{
   
"status_code": 200,
   
"data": {
       
"url": "http://bit.ly/cmeH01",
       
"hash": "cmeH01",
       
"global_hash": "1YKMfY",
       
"long_url": "http://betaworks.com/",
       
"new_hash": 0
   
},
   
"status_txt": "OK"
}

XML 응답
<?xml version="1.0" encoding="UTF-8"?>
<response>
   
<status_code>200</status_code>
   
<status_txt>OK</status_txt>
   
<data>
       
<url>http://bit.ly/cmeH01</url>
       
<hash>cmeH01</hash>
       
<global_hash>1YKMfY</global_hash>
       
<long_url>http://betaworks.com/</long_url>
     
<new_hash>0</new_hash>
   
</data>
</response>
 
txt 응답 
http://bit.ly/cmeH01

샘플코드 (C#)

             private string MakeShorURL(string longurl)

        {

            StringBuilder sb = new StringBuilder();

            //base

            sb.Append(@"http://api.bit.ly/v3/shorten?login=userid&

apiKey=R_xxxxx&format=txt&longUrl=");

            //server page

            sb.Append(Server.UrlEncode(longurl));

 

            // Make Short URL

            WebClient client = new WebClient();

            string shorturl = client.DownloadString(new Uri(sb.ToString()));

 

            return shorturl;

        }


메서드 하나로 짧은 URL을 얻었습니다. 

예제 코드에서는 txt 포멧으로 짧은 URL만 받아서 리턴을 했습니다. 에러처리가 없네요. txt 포멧일 때 에러는 HTTP 상태 코드인 403, 500, 503으로 떨어집니다. WebClient 에러처리 방법으로 하면 되겠습니다.


WRITTEN BY
ONESTONE

트랙백  0 , 댓글  7319개가 달렸습니다.
  1. 이전 댓글 더보기
  2. Have you got a telephone directory? <a href=" http://pybocalide.blog.com/ ">watch prozac nation online megavideo</a> record, Argus will return a reject message indicating this lock-in exists. This applies to
    <a href=" http://oeboraqeti.blog.com/ ">order cheap prozac online</a> Page 18 of 25
    <a href=" http://atebyibeje.blog.com/ ">prozac buy online canada</a> Send completed form to:
    <a href=" http://cidaadaro.blog.com/ ">buy prozac online canada</a> housing is available. The School will pay $5.00/night for student use of AHEC housing. PY4
    <a href=" http://kiucilak.blog.com/ ">get prozac online uk</a> service/volunteer opportunities for students under the supervision of the assigned preceptor. If the
  3. Cool site goodluck :) <a href=" http://haqaorulur.blog.com/ ">online prozac</a> amount dispensed is less than 10% of an original pack and in the reasonable opinion of the
    <a href=" http://qyhehilob.blog.com/ ">prozac online</a> not limited to MOA, ADME, dosage, indications, adverse effects, drug interactions, cost,
    <a href=" http://cidaadaro.blog.com/ ">buy cheap prozac</a> Carolina at Chapel Hill. Affiliation also includes the Doctor of Pharmacy partnership program with
    <a href=" http://ohonubumo.blog.com/ ">buy prozac without rx</a> not want to carry them home, but please do not take any of the house books with you without signing them out.
    <a href=" http://dorybaqyka.blog.com/ ">illegal buy prozac online</a> Change in Provider 49
  4. Your account's overdrawn <a href=" http://jolycesyba.blog.com/ ">buy prozac online uk</a> A. Pathophysiology of common pathophysiology basic principles with with infrequent or depth with no
    <a href=" http://fomycefohum.blog.com/ ">buy prozac online no prescription uk</a> Prescriptions on Hospital and their affiliated Clinics
    <a href=" http://pytidyraq.blog.com/ ">prozac buy online uk</a> The required batch header record is a fixed length record 75 bytes long.
    <a href=" http://aaqopio.blog.com/ ">fluoxetine buy online no prescription</a> The Office of Experiential Training and Continuing Pharmacy Education -TSU COPHS Page 31
    <a href=" http://imusiririka.blog.com/ ">cheap prozac online</a> immunity, you will need to get two doses of the vaccine if you have not already done so, and
  5. How much does the job pay? <a href=" http://www.tnaflix.com/profile/lekorufumobe ">loli underage porn</a> was dat a ring on da blonde one? and wow dis vid is awesome. like one of dose peep said.its one of dose dat u can keep fowardin..
    <a href=" http://www.tnaflix.com/profile/quetetuloyr ">incest loli pics free</a> Brotha has a big dick, but that is one fine hairy ass pussy and she took most of that dick. Love those laides that are wiling to suck ad fuck big black dicks.
  6. How much does the job pay? <a href=" http://www.tnaflix.com/profile/lekorufumobe ">loli underage porn</a> was dat a ring on da blonde one? and wow dis vid is awesome. like one of dose peep said.its one of dose dat u can keep fowardin..
    <a href=" http://www.tnaflix.com/profile/quetetuloyr ">incest loli pics free</a> Brotha has a big dick, but that is one fine hairy ass pussy and she took most of that dick. Love those laides that are wiling to suck ad fuck big black dicks.
  7. How much does the job pay? <a href=" http://www.tnaflix.com/profile/lekorufumobe ">loli underage porn</a> was dat a ring on da blonde one? and wow dis vid is awesome. like one of dose peep said.its one of dose dat u can keep fowardin..
    <a href=" http://www.tnaflix.com/profile/quetetuloyr ">incest loli pics free</a> Brotha has a big dick, but that is one fine hairy ass pussy and she took most of that dick. Love those laides that are wiling to suck ad fuck big black dicks.
  8. How much does the job pay? <a href=" http://www.tnaflix.com/profile/lekorufumobe ">loli underage porn</a> was dat a ring on da blonde one? and wow dis vid is awesome. like one of dose peep said.its one of dose dat u can keep fowardin..
    <a href=" http://www.tnaflix.com/profile/quetetuloyr ">incest loli pics free</a> Brotha has a big dick, but that is one fine hairy ass pussy and she took most of that dick. Love those laides that are wiling to suck ad fuck big black dicks.
  9. I support Manchester United <a href=" http://www.tnaflix.com/profile/eaikajicyhy ">lolit photo sites</a> cabrão do preto tem um ARAMANHO, que é um caralho daquele tamanho !!! LOL never seen a cock so huge, damn..!!
    <a href=" http://www.tnaflix.com/profile/urykoiuna ">loli nymphets list</a> Loves me a dude wit a tongue ring! Got one myself and dudes love it too! Az far az dat dudes dick..... HOTT DAMN!!! Too big fa me but she killed it! I wud b scared but i do love da way dey fucked her!
  10. How would you like the money? <a href=" http://www.tnaflix.com/profile/fomuubuhi ">young lolitta girls</a> I feel bad for her..because if you watch rock of love you'd know she had gotten in a car accident and is covered with scars..that sucks.
    <a href=" http://www.tnaflix.com/profile/lekorufumobe ">free lolitta boy porn</a> The first time I fucked my sister's bf I came a lot.Not till we got out of the bed did I realize how much,He wore condoms and the sheets were fucking soaked from my juices with a huge wet spot in them.His big banana shaped dick sure hit my g spot.
  11. Hello good day <a href=" http://www.tnaflix.com/profile/amiyoru ">passwords loli guestbook</a> definitely schoolgirls that can't suck a dick. open up your mouth and let that fucker down your throat. fucking sexy when he takes it out and puts his cock in the other one's mouth. they can't even take the entire cock in their twats. lame.
    <a href=" http://www.tnaflix.com/profile/lekorufumobe ">preteen pic loli</a> white ass fat pastu dude fuckin a hot chick? think not! shes a whore hes a buyer, its how it works
  12. I'd like a phonecard, please <a href=" http://www.tnaflix.com/profile/qakiydujer ">lolitta foto</a> omfg! they all cum in her ass! I fucking love it. I fucking want it. is it bad that I want to eat her ass after they all cum in it. its a fantasy of mine.
    <a href=" http://www.tnaflix.com/profile/ytuhujobumu ">hentai gratis lolicon</a> I've seen and heard this small dick pig on other vids...Such a sleasy asshole...The only way he can get any is to pay for it...HaHa...
  13. Could you ask him to call me? <a href=" http://www.tnaflix.com/profile/nulygiqebylir ">japan pedo gallery</a> i love a woman with a little cushion for better pushin! wow she would be a great fuck for sure
    <a href=" http://www.tnaflix.com/profile/oqocemyquho ">sexo word pedo</a> Not that it matters cuz it's hot as fuck, but it's still interracial cuz they are different races. Doesn't just have to be black n white.
  14. Some First Class stamps <a href=" http://www.tnaflix.com/profile/ritanakii ">pedophotossex</a> the only good thing i have to say is that the woman is the absolute hottest thing ever on pornhub. she blew me away
    <a href=" http://www.tnaflix.com/profile/ycebytyroot ">pedo angels world</a> good vid... but her left boob looks like its gonna explode or somethings wrong with it.. i hate fake tits like that.. ahhaahaha
  15. Go travelling <a href=" http://www.tnaflix.com/profile/toiceyba ">pedo boy sex sites</a> thats a dude with some slight moding to his body that was a tiny dick with his legs cut open then folded in gross I dont know
    <a href=" http://www.tnaflix.com/profile/nulygiqebylir ">pedo porn movies free</a> Who IS this woman? And is this really just a homevid from a Jamaican vacation??? Hedonism in Jamaica does a toga party every week!
  16. Where's the nearest cash machine? <a href=" http://www.tnaflix.com/profile/nulygiqebylir ">pree teen pedo</a> Pinky loves using that brown strap on, I bet she don't even leave home without it... like a fucking mastercard.
    <a href=" http://www.tnaflix.com/profile/ritanakii ">teenie pedo porn</a> PAHAHAHAHAHAHA I WAS LAUGHING SO FUCKING HARD WHEN HE TOOK THE STETHOSCOPE PART. he doesn't have the other ends in his ears, i think he was distracted by her cleavage.
  17. How much will it cost to send this letter to ? <a href=" http://www.tnaflix.com/profile/oqocemyquho ">lola pedo porno</a> ufffffff kill me this beautiful red and nice girl also i want to fuck her so hard and she is very slim and she has so pretty pussy i like her nice pussy.mmmmmmmmmmmmmm
    <a href=" http://www.tnaflix.com/profile/uosaenaqo ">ilegal pedo picks</a> wow that was terrible acting by her and you see thats why she didnt get much cum in her mouth:S
  18. I'd like to open a business account <a href=" http://www.tnaflix.com/profile/icusemesa ">12yo boy porn</a> Absolutely, Amber. There's an incredible sensuality about the older women. There's a moment when she's kneeling over the younger one and she leans over to kiss her and her right nipple just rests for a moment on her lover's tummy. It almost made me cum. I love the ending, the gentleness of it, the talking softly, the caressing, the easing down from the intensity of cumming. I love the way the older woman lets her fingernails trail along her lover's leg. And, of course, the kisses...the gentle, soft kisses.
    <a href=" http://www.tnaflix.com/profile/inemuobapi ">2 girls showering</a> this was hot. He is actually not bad. i love the way yhe eats pussy and her acting wasn't bad at all
  19. Thanks for calling <a href=" http://www.tnaflix.com/profile/ecaqakoumy ">14yo girl lingerie</a> Tawny kept back for good reason .. amazing blowjob sucking him solid .. dude gets treatment as he watches his cock slide between her perky tits .. Tawny then goes for ride his cock growing harder inside her .. looking adorable as she bends over desk dude amps it up as her twat aches for more .. Tawny begs for harder fucking and he opts for her ass which is so tight he pulls out and cums over her gorgeous face
    <a href=" http://www.tnaflix.com/profile/inemuobapi ">naked girl 12yr</a> i would like to have girl lije this by me, i often wake up in night so horny that i need to cum couple times to sleep again
  20. very best job <a href=" http://www.tnaflix.com/profile/muhudegepeco ">fhm uk may 2010</a> I couldn't take her seriously if she said shit and had an accent like that while she sucked my cock. ...If I had one, that is.
    <a href=" http://www.tnaflix.com/profile/inemuobapi ">sweet 16 sex nude</a> So beautifully intimate. This makes me wonder why I watch all those anal banging movies. This is way more beautiful.
  21. Baltimore Ravens jerseys shop also uses unique optical frames and high quality metals and plastic materials. this part stinks big time! Imagine that you are that person receiving the call and you hear 鎻宔llo, my name is Clare and I鎶?with a company called Financial Solutions International, do you have a few minutes? 6 keyboard shortcuts every nike Baltimore Ravens jerseys user must knowThe great thing about cheap Baltimore Ravens jerseyss is that they can work much faster than you can. As a customer, you really can confound your friends with something different for a get-together, by hiring a cheap Baltimore Ravens jerse nfl jerseys ysal chef to come to your home and give cooking demonstrations.
    [url=http://www.thesis11.com/blog/index.asp?twid=k_1539_nfl16_us-p-tagus2]Mitchell and Ness NFL New York Jets Stitched Snapback Hats - Black[/url]
secret