Mobile Dev/Android2010. 11. 30. 11:22
모바일 앱을 만들다보면 의외로 Shorten URL이 많이 필요하게 된다.
Shorten URL을 공짜로 서비스하며 그 중에서 API를 제공하는 사이트도 다수가 있다.
그중에서 가장 많이 사용하는 bit.ly 사이트의 API를 이용하여 Shorten URL을 연동하는 방법을 알아본다.

참고로 code.google.com에서 bit.ly로 검색해보면 오픈된 프로젝트가 있으나, 난 그냥 Shorten URL을 연동하는 것만 만들어서 사용했다.

1. 인증
bit.ly의 API를 사용하기 위해서는 bit.ly의 계정과 api key가 필요하다.

1. bit.ly에 계정을 생성한다. 계정이 존재한다면 그냥 사용해도 된다. (http://bit.ly/a/sign_up)
2. bit.ly 사이트에 로그인하고 사용할 개인 api key를 발급 받는다. (http://bit.ly/a/your_api_key)

이 두단계면 인증절차를 위한 준비는 완료이다. 또, bit.ly에 계정을 만들면 자신이 생성한 Shorten URL에 대한 히스토리를 확인 할 수도 있다.

2. Shorten URL 연동
Shorten URL을 연동하기 위한 방법으로 api url을 직접 호출하여 결과를 얻어오는 방식을 이용한다.
결과에 대한 포맷은 여러가지가 존재하지만 XML 포맷을 선택했다.

연동 절차는 아주 간단하다.
1. Shorten URL을 제공하는 api url을 호출한다. (요청 파라미터 포함)
2. 응답 XML을 파싱한다.

API URL : http://api.bit.ly/v3/shorten
Request Parameter
    - login : 인증 할 계정 아이디
    - apiKey : 계정으로 발급 받은 개인 api key 값
    - format : 응답 포맷
    - longUrl : Shorten URL로 변환 할 Long URL (URLEncoder 해서 사용한다.)
물론 Get/Post 둘다 가능하다.
예) http://api.bit.ly/v3/shorten?login=[아이디]&apiKey=[개인 api key]&format=[응답 포맷]&longUrl=[원본 URL]

Shorten URL 연동 결과 XML 
<?xml version="1.0" encoding="utf-8" ?> 
<response>
    <status_code>200</status_code> 
    <status_txt>OK</status_txt> 
    <data>
        <url>http://bit.ly/i35TSJ</url> 
        <hash>i35TSJ</hash> 
        <global_hash>3GtD5m</global_hash> 
        <long_url>http://www.naver.com</long_url> 
        <new_hash>0</new_hash> 
    </data>
</response>

API 연동 부분 (HttpClient의 Get 방식을 이용)
public String getShortUrl(String longUrl) throws Exception {
  String shortUrl = null;

  HttpClient httpClient = null;
  try {
     httpClient = new HttpClient();

     StringBuilder bitlyUrl = new StringBuilder("http://api.bit.ly/v3/shorten"));
     bitlyUrl.append("?");
     bitlyUrl.append("login").append("=").append("ukzzang").append("&");
     bitlyUrl.append("apiKey").append("=").append("xxxxxxxxxxxxxxx").append("&");
     bitlyUrl.append("format").append("=").append("xml").append("&");
     bitlyUrl.append("longUrl").append("=").append(URLEncoder.encode(longUrl));

     InputStream in = null;
     try {
        in = httpClient.requestGet(bitlyUrl.toString()); // api call (get method)

        BitLyResponseParser parser = new BitLyResponseParser();
        BitLyResultInfo resultInfo = parser.parseXml(in, "utf-8"); // 응답 XML 파싱

        if (resultInfo.getStatusCode() == 200) {
           shortUrl = resultInfo.getUrl();
        } else {
           throw new Exception(resultInfo.getStatusCode() + ":" + resultInfo.getStatusTxt());
        }
     } finally {
        if (in != null) {
           in.close();
           in = null;
        }
     }
  } finally {
     if (httpClient != null) {
        httpClient.shutdown();
        httpClient = null;
     }
  }

  return shortUrl;
}

응답 XML을 파싱하는 Parser
// bit.ly response xml parser
private class BitLyResponseParser extends ApiXmlParser {
  public BitLyResponseParser() throws XmlPullParserException {
     super();
  }

  @Override
  public BitLyResultInfo parseXml(InputStream inputStream,
        String inputEncoding) throws Exception {
     BitLyResultInfo resultInfo = null;

     parser.setInput(inputStream, inputEncoding);
     int mParserEvent = parser.getEventType();
     String mTag = null;

     while (mParserEvent != XmlPullParser.END_DOCUMENT) {
        switch (mParserEvent) {
         case XmlPullParser.START_TAG:
            mTag = parser.getName();

            if ("response".compareTo(mTag) == 0) {
               if (resultInfo == null) {
                  resultInfo = new BitLyResultInfo();
               }
            } else if ("status_code".compareTo(mTag) == 0) {
              resultInfo.setStatusCode(Integer.parseInt(parser .nextText()));
            } else if ("status_txt".compareTo(mTag) == 0) {
               resultInfo.setStatusTxt(parser.nextText());
            } else if ("url".compareTo(mTag) == 0) {
               resultInfo.setUrl(parser.nextText());
            } else if ("hash".compareTo(mTag) == 0) {
               resultInfo.setHash(parser.nextText());
            } else if ("global_hash".compareTo(mTag) == 0) {
               resultInfo.setGlobalHash(parser.nextText());
            } else if ("long_url".compareTo(mTag) == 0) {
              resultInfo.setLongUrl(parser.nextText());
            }

            break;
         }

         mParserEvent = parser.next();
      }

      return resultInfo;
   }
}

public class BitLyResultInfo {
  private int statusCode = 200; // status code (200 성공)
 
private String statusTxt = null; // status text

 
private String url = null; // short url
 
private String hash = null; // hash
 
private String globalHash = null; // global hash
 
private String longUrl = null; // original long url

  // ******************** 아래에 getter and setter method 명시
}

위의 소스를 이용하면 손쉽게 bit.ly의 Shorten URL을 연동할 수 있다.
Posted by as.wind.914