最近在用网易云短信时,需要发送链接地址,但是链接地址过长发送不了,就想到怎么把域名缩短,就百度出来。
图文解释:
- 第一步:
- 第二步:如果不需要代码,可以手动生成。
- 第三步:微信扫码登录
- 第四步:登录以后进入后台,点击API查询key和API接口文档
解释一下这个文档:
- urlencode(‘http://www.baidu.com’) 这个地方需要转换字符集编码
- 日期是链接在缩短之后的有效期。
代码案例:
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* TODO
*
* @author 码农老中医
* @date 2019/8/28 10:47
*/
public class Test2 {
private static final String KEY = "后台点击API查询自己的key";
private static String getNextDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, +2);//+1今天的时间加一天
date = calendar.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
public static void main(String[] args) throws Exception {
// 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpclient = HttpClients.createDefault();
String param = "https://www.baidu.com";
// 没有使用urlencode编码
String URL = "http://suo.im/api.htm?format=json&url=" + param + "&key=" + KEY + "&expireDate=" + getNextDay(new Date());
// 创建HttpGet请求,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet(URL);
CloseableHttpResponse response = null;
try {
// 执行请求,相当于敲完地址后按下回车。获取响应
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应,获取数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("转换的为:" + content);
JSONObject json = JSONObject.parseObject(content);
String err = json.getString("err");
System.err.println(err);
if (StrUtil.isEmpty(err)) {
String url = json.getString("url");
System.err.println(url);
}
}
} finally {
if (response != null) {
// 关闭资源
response.close();
}
// 关闭浏览器
httpclient.close();
}
}
}
在content 会返回一个json串,格式如:{“err”:"",“url”:“http://suo.im/4LIXzV”}
代码比较少,很简单,但是很实用,欢迎关注我的微信公众号一起探讨Java相关技术开发。
注意:如果你在生成的链接量比较大时,可能需要付费,如果量小,是免费使用的。