public class ShortUrlUtils {
private static Logger logger = Logger.getLogger(ShortUrlUtils.class);
/**
* 調用新浪短網址API接口
* @param requertUrl:新浪接口Url
* @param appkey
* @param longUrl:長網址
* @return
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getSinaShortUrl(String requertUrl, String appkey, String longUrl) {
String shortUrl = "";
try{
List
if(null != list && !list.isEmpty()){
Map map = list.get(0);
if(null != map && !map.isEmpty()){
String returnLongUrl = map.containsKey("url_long") ? map.get("url_long").toString() : "";
String returnShortUrl = map.containsKey("url_short") ? map.get("url_short").toString() : "";
if(!longUrl.equals(returnLongUrl) && !longUrl.equals(urlEncodeUTF8(returnLongUrl))){
throw new Exception("轉換前後的長鏈接地址不一致!");
}else{
shortUrl = returnShortUrl;
}
}
}
} catch (Exception e) {
logger.error("調用新浪短網址API接口異常:"+ e);
}
return shortUrl;
}
/**
* @param requertUrl
* @param longUrl
* @return
*/
@SuppressWarnings("rawtypes")
public static String getBaiduShortUrl(String requertUrl, String longUrl) {
String shortUrl = "";
try{
Map map = (Map) UrlUtil.sendUrl(requertUrl, "POST", "url="+ longUrl, "UTF-8", 1);
if(null != map && !map.isEmpty()){
String status = map.containsKey("status") ? map.get("status").toString() : "";
if("0".equals(status)){
String returnLongUrl = map.containsKey("longurl") ? map.get("longurl").toString() : "";
String returnShortUrl = map.containsKey("tinyurl") ? map.get("tinyurl").toString() : "";
if(!longUrl.equals(returnLongUrl) && !longUrl.equals(urlEncodeUTF8(returnLongUrl))){
throw new Exception("轉換前後的長鏈接地址不一致!");
}else{
shortUrl = returnShortUrl;
}
}else{
String errMsg = map.containsKey("err_msg") ? map.get("err_msg").toString() : "";
throw new Exception(errMsg);
}
}
} catch (Exception e) {
logger.error("調用百度短網址API接口異常:"+ e);
}
return shortUrl;
}
/**
* URL編碼(utf-8)
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
閱讀更多 熱血萌寵 的文章