如何生成短链接


/**
 *	调用新浪微博生成短链接
 */
public class ShortUrlUtil {
	public static String getShortUrl(String long_url) {
		String result = sendGet("http://api.t.sina.com.cn/short_url/shorten.json?source=3113722175&url_long=",long_url);
		String shortUrl = null;
		if(StringUtils.isNotBlank(result)){
			Map map = JsonUtils.deserializeJson(result.substring(1, result.length()-1));
			if(map.get("url_short") != null) {
				shortUrl = (String) map.get("url_short");
			}
		}
		return shortUrl;
	}

	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			// 获取所有响应头字段
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常!" + e);
			//e.printStackTrace();
		}
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println(getShortUrl("https://www.baidu.com/"));
	}
}

猜你喜欢

转载自blog.csdn.net/qq_31024823/article/details/82812705
今日推荐