老师能更新下源码用新浪或者微信的免费的短链接接口吗, 下面是我看有个同学用的微信短链接接口的方法 ,不知道到导入什么依赖,无法解决。。。那个百度短链接收费太贵了…而且每次点击都要钱…
public class ShortNetAddressUtil {
static String appid = “你的appid”;
static String appsrcret = “你的appsrcret”;
public static void main(String[] args) {
String longUrl = "https://baidu.com";
System.out.println(getShortURL(longUrl));
}
/**
* 微信根据APPID和APPSECRET获取token
*
* @param appid
* @param appsrcret
* @return 返回转换后的短链接
*/
public static String getToken(String appid, String appsrcret) throws Exception {
// 访问地址
String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
String APPID = appid;
String APPSECRET = appsrcret;
String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = HttpUtils.httpsUtil(request_url, "GET", null);
if (null != jsonObject) {
String access_token = jsonObject.getString("access_token");
return access_token;
}
return null;
}
/**
* 将长链接转为短链接(调用的微信短网址API) 需要token
*
* @param longUrl 需要转换的长链接url
* @param appid
* @param appsrcret
* @return 返回转换后的短链接
*/
public static String getShortURL(String longUrl) {
ResultBean<String> result = new ResultBean<>();
String token;
try {
token = getToken(appid, appsrcret);
String uri = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
String url = uri.replace("ACCESS_TOKEN", token);
String param = "{"action":"long2short"," + ""long_url":"" + longUrl + ""}";
// 调用接口创建菜单
JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", param);
System.out.println(jsonObject);
if (null != jsonObject) {
result.setCode(jsonObject.getInteger("errcode"));
result.setData(jsonObject.getString("short_url"));
return result.getData();
} else {
return null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
登录后可查看更多问答,登录/注册
SSM商铺V1.0,解决毕设痛点;SpringBoot商铺V2.0,满足工作刚需
了解课程