PHP实现长链接转化成新浪短链接API接口代码分享

我们可能会收到类似于这样的短信,发现其中的链接并不是常规的网址链接,而是个短小精悍的短链接,产品中经常需要这样的需求,如果在给用户下发的短信中是一个很长的连接,用户体验肯定很差,因此我们需要实现长链接转换成短链接。.

今天我就给打分享一个利用php调用新浪短链接/腾讯短链接AP接口的方法。分享给大家供大家参考使用。

接口地址

新浪短网址接口地址: 

http://www.sinadwz.cn/sina.php?url_long=http://www.baidu.com

说明:将上面短网址api接口的标红部分的链接替换成需要缩短的长连接即可!


接口文档

PHP调用代码:

$url = 'http://www.baidu.com';
$api_url = ''.urlencode($url);
$short_url = file_get_contents($api_url);
echo $short_url;



其他语言调用文档

JAVA调用代码:

 public static void main(String path[]) throws Exception {
    URL u = new URL("http%3A%2F%2Fwww.baidu.com");
    InputStream in = u.openStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
    byte buf[] = new byte[1024];
    int read = 0;
    while ((read = in .read(buf)) > 0) {
    out.write(buf, 0, read);
    }
    } finally {
    if ( in != null) {
    in .close();
    }
    }
    byte b[] = out.toByteArray();
    System.out.println(new String(b, "utf-8"));
    }

Python调用代码:

  import urllib, urllib2, sys
    host = ''
    path = ''
    method = 'GET'
    querys = 'http%3A%2F%2Fwww.baidu.com'
    bodys = {}
    url = host + path + '?' + querys
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    content = response.read()
    if (content):
    print(content)

注意事项:

1、使用api接口时,只需将 URL=后的链接替换成自己这边需要缩短的长链接即可。

2、接口支持参数传递,当链接中出现 & 符号时,请用 %26 代替(或者使用url编码),否则携带的参数会丢失。

3、填写链接时,必须使用http(s)://协议,否则API接口将会无法生成短链接!


猜你喜欢

转载自www.cnblogs.com/asda/p/11976463.html