Google 已经有一个 URL 缩短域名很长一段时间了,但直到最近 Google 才向公众公开了 URL 缩短 API。我花了几分钟查看他们的 API 并创建了一个非常基本的 GoogleUrlApi 类,它将缩短长 URL 并扩展缩短的 URL。
PHP
类本身非常紧凑,代码应该易于阅读:
// Declare the class
class GoogleUrlApi {
// Constructor
function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
// Keep the API Url
$this->apiURL = $apiURL.'?key='.$key;
}
// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response['id']) ? $response['id'] : false;
}
// Expand a URL
function expand($url) {
// Send information along
$response = $this->send($url,false);
// Return the result
return isset($response['longUrl']) ? $response['longUrl'] : false;
}
// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}
构造函数需要您的 Google API 密钥。可以向 Google API 的 URL 提供第二个参数。由于 API 当前处于版本 1,因此更改此 URL 弊大于利。该类具有两种主要方法:缩短和扩展。每种方法都采用长 URL 或短 URL,联系 Google,然后返回其对应的方法。如果找不到对应项,或者 Google URL Shortener API 已关闭,则会返回 false 结果,因此请务必使用您自己的错误处理。
现在让我们创建一个 GoogleUrlApi 实例来缩短然后扩展 URL:
// Create instance with key
$key = 'xhjkhzkhfuh38934hfsdajkjaf';
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten("https://davidwalsh.name");
echo $shortDWName; // returns http://goo.gl/i002
// Test: Expand a URL
$longDWName = $googer->expand($shortDWName);
echo $longDWName; // returns https://davidwalsh.name
shorten() 和 expand() 方法按预期返回它们的对应项。很轻松,不是吗?
Google URL Shortener API 提供的功能远远超过我的课程,包括用户 URL 列表和使用情况跟踪。我的课只提供基础知识;我假设 90% 以上的人只关心缩短 URL,所以我已经迎合了这些观众。我也考虑过在类中添加缓存机制,但由于大多数人都有自己的缓存信息方法,所以我认为最好将其排除在外。希望这门课对你们都有用!
