2. 注册为开发者并创建应用获取appkey
独立开发者appkey使用期限好像只有一天
3. 需要引入的pom
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
4.源码
public class XLUrlUtil {
static Logger logger = LoggerFactory.getLogger(XLUrlUtil.class);
private static String SOURCE="请输入注册的appkey";
private static String XL_SHORT_API="http://api.t.sina.com.cn/short_url/shorten.json?";
private static String XL_LONG_API="http://api.t.sina.com.cn/short_url/expand.json?";
public static String getShortUrl(String long_url) {
if(long_url == null || long_url.equals("")){
return null;
}
//调用服务端
try {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
URL url = new URL(XL_SHORT_API.concat("source=").concat(SOURCE).concat("&url_long=").concat(URLEncoder.encode(long_url,"UTF-8")));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
System.out.println(result);
JSONArray shortURLs=JSONArray.parseArray(result);
if(shortURLs.size()==1){
JSONObject url_short =shortURLs.getJSONObject(0);
return url_short.getString("url_short");
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("appList接口异常,异常信息:" + e.getMessage() + "异常详情: ");
logger.error("短连接生成失败,请稍后再试...");
}
return null;
}
public static String getLongUrl(String short_url) {
if(short_url == null || short_url.equals("")){
return null;
}
//调用服务端
try {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
URL url = new URL(XL_LONG_API.concat("source=").concat(SOURCE).concat("&url_short=").concat(URLEncoder.encode(short_url,"UTF-8")));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
System.out.println(result);
JSONArray shortURLs=JSONArray.parseArray(result);
if(shortURLs.size()==1){
JSONObject url_short =shortURLs.getJSONObject(0);
return url_short.getString("url_long");
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("长连接生成失败,请稍后再试...");
}
return null;
}
public static void main(String[] args) {
System.out.println(getShortUrl("需要转换的长链接"));
System.out.println(getLongUrl("需要还原的短链接"));
}
}