转载

短网址链接生成器代码示例——新浪短链接api接口php、java、Python调用演示

短网址api对接成了大家经常遇到的难题,今天以 t.cn短链接api接口 为例给出三种语言的调用示例代码:

1.APIKEY获取:

http://url-t.cn/api

2.调用代码

PHP调用代码

$url = 'http://www.baidu.com'; 
$api/_url = 'http://url-t.cn/tcn/api?key=APIKEY/tcn/_url?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://url-t.cn/tcn/api?key=APIKEY&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 = 'http://url-t.cn' 
path = '/tcn/api' 
method = 'GET' 
querys = 'key=APIKEY&url=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)

3.对接提示:

  • a.长链接需要url编码,尤其是链接后带参数的,一定要先经过编码
  • b.长链接需要带协议头, http:// 或者 https://
  • c.APIKEY是唯一识别码,需要在对接前换成自己的KEY
  • d.代码建议加异常处理,因为网络通畅性的缘故,超时异常有可能会发生
原文  https://segmentfault.com/a/1190000022428942
正文到此结束
Loading...