代码调用t.cn接口生成短址

新浪短网址接口的稳定性和跳转速度还是很给力的,现给出其API说明。
该接口支持两种返回格式:xml和json
对应的URL请求地址为:


xml:http://api.t.sina.com.cn/short_url/shorten.xml
json:http://api.t.sina.com.cn/short_url/shorten.json

请求方式:GET
请求参数:
  source:应用的appkey
  url_long:需要转换的长链接

举个例子:

json:http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=https://blog.csdn.net/iku5200
返回内容为:
[{"url_short":"http://t.cn/zWXySpZ","url_long":http://www.douban.com/note/249723561/","type":0}]


xml:http://api.t.sina.com.cn/short_url/shorten.xml?source=3271760578&url_long=https://blog.csdn.net/iku5200
返回内容为:
<urls>
     <url>
          <url_short>http://t.cn/zWXySpZ</url_short>
          <url_long>http://www.douban.com/note/249723561/</url_long>
          <type>0</type>
     </url>
</urls>

下面是python调用代码示例:

def get_short_url(url):

    host = 'http://api.t.sina.com.cn/short_url/shorten.json'
    path = '?source=3271760578&url_long={}'.format(url)
    url2 = host + path

    # 发起请求
    response = requests.get(url=url2)

    # 返回响应
    url_short = response.json()[0]['url_short']

    return url_short


 

posted @ 2019-02-20 16:33  海岛拾贝  阅读(532)  评论(0编辑  收藏  举报