package cn.com.countrygarden.bi.main.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * class_name: ShortUrlUtil
 * package: cn.com.countrygarden.bi.main.util
 * describe: 短连接生成工具类
 * creat_user: justintoforest@gmail.com
 * creat_date: 2018/7/13
 * creat_time: 10:02
 **/
public class ShortUrlUtil {

	private final static String appKey="3271760578";

	/**
     * 获取短连接
	 * @param longUrl 放置源链接
	 * @return
     */
    public static String getShortUrl(String longUrl) {
		try {
			longUrl=URLEncoder.encode(longUrl, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String result = doGet("http://api.t.sina.com.cn/short_url/shorten.json?source="+appKey+"&url_long="+longUrl);
		JSONArray array = JSONArray.parseArray(result);
		JSONObject jo = array.getJSONObject(0);
		String url_short = jo.getString("url_short");
		return url_short;
	}
 

	private static String doGet(String url){
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			response = httpclient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static void main(String[] args) {
		System.out.println(getShortUrl("http://duptest.bgyfw.com:8001/static/answerpage/answer.html?iid=27&jid=60&qid=17"));
	}

}
