Using Baidu’s Short URL API to Generate Short URLs from an HTML Single Page
Not long ago, I wrote an article titled “jQuery Online Generation of t.cn Sina Short URLs,” which used Sina Weibo’s short URL interface. I gradually developed an interest in short URLs, so I specifically looked for some open short URL interfaces.
Today I’m going to talk about Baidu’s short URL interface and share my experience and the finished code below. (Baidu short URLs support only a small number of domains. I’m not sure about the specific rules, so this article is not particularly useful and is for learning purposes only.)
Getting Started
First, the API request URL for Baidu short URLs is: http://dwz.cn/create.php
Only post submissions are allowed.
The request parameters include two fields: url and alias. The first parameter is the long URL (required), and the second parameter is a custom URL (optional).
Returned data: data in json format.
status = 0 indicates an error; check err_msg for the error message (UTF-8 encoding).
status = -1 indicates success; the returned tinyurl is the short URL.
Finished Code
<?php
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,"http://dwz.cn/create.php");
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$data=array('url'=>'http://www.baidu.com/');
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$strRes=curl_exec($ch);
curl_close($ch);
$arrResponse=json_decode($strRes,true);
if($arrResponse['status'] == 0)
{
echo iconv('UTF-8','GBK',$arrResponse['err_msg']);
}
echo $arrResponse['tinyurl'].; //输出短网址
?>
Baidu’s short URL service is not more useful than Sina’s, so I still recommend using Sina’s short URL service.
Comments
(1)一直用的雷虎短链