2016. 10. 6. 17:15
반응형

goo.gl 를 정상적으로 사용하려면 먼저 구글 프로젝트를 만들고 구글 API에서 URL Shortener API 를 찾아서 사용함으로 변경해야 되는데 꾀나 복잡하다.

구글 API를 사용하게 되면 key를 제공해 준다.

key를 넣지 않아도 API의 사용은 가능한것 같은데 key가 있으면 생성된 url에 대해서 통계 자료를 제공해 주고 역변환 (short url -> long url) 기능도 제공되는것 같다.

생성제한은 키당 하루에 100만개 까지 가능함. (1,000,000)


import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLSession;


public String urlShortener(String longUrl) throws Exception {

HttpsURLConnection con = null;

String res = "";

try {

String url = "https://www.googleapis.com/urlshortener/v1/url?key=[YOUR_KEY]";

String param = "{\"longUrl\":\"" + longUrl + "\"}";

con = (HttpsURLConnection) new URL(null, url, new sun.net.www.protocol.https.Handler()).openConnection();

con.setHostnameVerifier(new HostnameVerifier() {

public boolean verify(String hostname, SSLSession session) {

return true;

}

});

con.setRequestMethod("POST");

con.setRequestProperty("Content-Type", "application/json");

con.setDoOutput(true);

OutputStream os = con.getOutputStream();

os.write(param.getBytes());

os.flush();

os.close();

StringBuffer sb = new StringBuffer();

if(con.getResponseCode() == 200) {

InputStream is = con.getInputStream();

byte[] read = new byte[1024];

while(is.read(read, 0, 1024) > -1) {

sb.append(new String(read).trim());

}

is.close();

JSONObject jsonObject = JSONObject.fromObject(sb.toString());

res = jsonObject.get("id").toString();

} else {

throw new Exception("responseCode is " + con.getResponseCode());

}

} catch(Exception e) {

logger.info("urlShortener error!!");

logger.error("", e);

} finally {

if(con != null) {

try {

con.disconnect();

con = null;

} catch(Exception e) {

}

}

}

return res;

}

반응형

'Java' 카테고리의 다른 글

tomcat localhost ssl 적용을 위한 키 생성  (0) 2021.02.05
RSA 암호화 java 구현 class  (0) 2018.02.23
bit.ly api java 구현  (0) 2016.10.06
Object와 Object[]에 대한 내용  (1) 2011.11.10
base64, DES chiper - encode, decode 구현  (6) 2011.10.11
Posted by seongsland