友情提示:
来源:14-11 店铺授权之短链接的实现
慕仔7496235
2019-09-08
各位小伙伴百度的的短链接API访问地址已经更改,请使用下面的链接https://dwz.cn/admin/v2/create,其中需要的参数token请访问https://dwz.cn/console/apidoc自行获取,另附上我整理的代码,仅供参考:
public class ShortNetAddressUtil {
final static String CREATE_API = “https://dwz.cn/admin/v2/create”;
final static String TOKEN = “你的token”;
class UrlResponse {
@SerializedName("Code")
private int code;
@SerializedName("ErrMsg")
private String errMsg;
@SerializedName("LongUrl")
private String longUrl;
@SerializedName("ShortUrl")
private String shortUrl;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public String getLongUrl() {
return longUrl;
}
public void setLongUrl(String longUrl) {
this.longUrl = longUrl;
}
public String getShortUrl() {
return shortUrl;
}
public void setShortUrl(String shortUrl) {
this.shortUrl = shortUrl;
}
}
/**
* 创建短网址
*
* @param longUrl
* 长网址:即原网址
* @return 成功:短网址 失败:返回空字符串
*/
public static String getShortURL(String longUrl) {
String params = "{"url":"" + longUrl + ""}";
BufferedReader reader = null;
try {
// 创建连接
URL url = new URL(CREATE_API);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.setRequestProperty("Token", TOKEN); // 设置发送数据的格式");
// 发起请求
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(params);
out.flush();
out.close();
// 读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
String res = "";
while ((line = reader.readLine()) != null) {
res += line;
}
reader.close();
// 抽取生成短网址
UrlResponse urlResponse = new Gson().fromJson(res, UrlResponse.class);
if (urlResponse.getCode() == 0) {
return urlResponse.getShortUrl();
} else {
System.out.println(urlResponse.getErrMsg());
}
return "";
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String res = getShortURL("https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login");
System.out.println(res);
}
}
另外还需要引入额外的jar包:
groupId:com.google.code.gson
artifactId:gson
亲测运行正常,可以生成对应的短链接,如果有问题,欢迎讨论
写回答
1回答
-
翔仔
2019-09-10
同学好,非常感谢同学的分享,经检查发现,短网址确实于近日进行了变更,这一变更比较不友好,直接将原来的接口取消,不是一个好的规范,同学做出的相关变更我于本周内将其放到最终源码里,然后在视频对应的地方设置矛点标注出来让大家看到。再次感谢同学:)
022019-10-24
相似问题