该方法适用于任何将长网址转换为短网址。
在二维码生成的时候因为二维码生成的类会根据传入的内容生成相对应的二维码,当内容越丰富时二维码的识别就比较复杂难以识别。在此时就需要用到。
短链接,通俗来说,就是将长的URL网址,通过程序计算等方式,转换为简短的网址字符串。有时也称短网址(Short URL)。
这里第三方接口使用nowapi , 注册网址:https://www.nowapi.com。通过注册得到appkey和sign。
接口文档地址(创建短网址接口):https://www.nowapi.com/api/shorturl.set。点击立即开通,可以直接选择创建三个月
开通之后,点页面的appKey就可以看见appkey和sign
申请好了之后直接将我编写好的这个类复制到java项目中即可使用。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
public class ShorturlUtil {
private static final String APPKEY = "49573";
private static final String SIGN = "f927c86588bfa0dfad26ad9b78b6a7a3";
//用来将长网址转换成短url的网址
private static final String resolveurl = "http://api.k780.com/";
//用来返回的短网址
private static String shorturl;
public static String longurl2Shorturl(String longurl) throws Exception {
//URL u=new URL("http://api.k780.com/?app=shorturl.set&url=需要缩短的网址(需要urlencode)&appkey={APPKEY}&sign={SIGN}&format=json");
URL u=new URL(resolveurl+"?appkey="+APPKEY+"&sign="+SIGN+"&format=json"+"&app=shorturl.set&url="+longurl);
InputStream inputStream=u.openStream();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(u.openStream());
shorturl = jsonNode.get("result").get("short_url").asText();
//有些地方对http会拦截,所以统一改成https
if (shorturl.startsWith("http:")){
shorturl = shorturl.replace("http:","https:");
}
return shorturl;
}
public static void main(String[] args) throws Exception {
String url = "http://open.weixin.qq.com/connect/oauth2/" +
"authorize?appid=wx4c00f63bf8fc13fb&redirect_uri=http://www.hujiatai.cn/wechatlogin/" +
"logincheck&response_type=code&scope=snsapi_userinfo&state="+ 1
+"#wechat_redirect";
System.out.println(longurl2Shorturl(url));
}
}
运行完成之后就会得到一个短网址。