使用twitter的api发消息时,如果想使用短网址的话,twitter api没有提供这个功能,使用google的api来生成短网址,是一个不错的选择!
2015-06-29 11:55:21
官网地址:https://developers.google.com/url-shortener/
需要Api key ,去https://console.developers.google.com/project这里申请就可以,新建立一个project后,在Apis的控制面板,把URL Shortener API这一项打开就可以了,然后在credential里create new key,就可以了!
使用curl请求的话
curl https://www.googleapis.com/urlshortener/v1/url?key=APIKEY -H 'Content-Type: application/json' -d '{"longUrl": "http://www.sina.com.cn/"}'
使用php请求的方法
$data = array("longUrl" => $url);
$data_string = json_encode($data);
$ch = curl_init('https://www.googleapis.com/urlshortener/v1/url?key=APIKEY');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = json_decode(curl_exec($ch));
$short_url = $result->id; //得到短网址