import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
private final String SHORT_URL_API ="http://tiny-url.info/api/v1/create";
//사이트에서 이메일주소를 넣고 요청을 하면 이메일로 apikey가 날아온다
//날아온 이메일에서 API Key Activation 이라고 되어있는 URL을 클릭하면 키가 사용가능한 상태가 된다.
//날아온 이메일에서 API Key Activation 이라고 되어있는 URL을 클릭하면 키가 사용가능한 상태가 된다.
private String createShortUrl(String longURL){ //긴 URL을 받아 단축 URL을 반환하는 메소드
try{
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpPost post = new HttpPost(SHORT_URL_API);
ArrayList param = new ArrayList(); //파라미터를 넣을 리스트
param.add(new BasicNameValuePair("apikey", API_KEY));
param.add(new BasicNameValuePair("provider", "dok_do")); //다양한 provider를 선택할 수 있음
param.add(new BasicNameValuePair("format", "json"));
param.add(new BasicNameValuePair("url", longURL)); //변환할 URL
UrlEncodedFormEntity entity = null;
try{
entity = new UrlEncodedFormEntity(param, "UTF-8"); //인코딩을 UTF-8로 entity를 생성
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == HttpStatus.SC_OK)
{
byte[] buffer = new byte[4096];
InputStream is = response.getEntity().getContent();
int len = -1;
StringBuffer jsonString = new StringBuffer();
while( (len = is.read(buffer)) != -1 )
jsonString.append(new String(buffer, 0, len));
JSONObject json = new JSONObject(jsonString.toString());
String url = json.getString("shorturl");
if(url == null) url = "";
return url; //생성된 단축 URL을 리턴
}
}
catch(Exception e){e.printStackTrace();}
return "";
}
반응형