Google URL Shortener API を使ってみる(2) - PHPで利用してみる

準備で取得したAPIキーを利用してGoogle URL Shortner API へアクセスすることで短縮したURLを取得することができる。
ここでは、PHP上から利用してみた例。HTTPのPOSTアクセスには、PEARのHTTP::Request2を利用しているので、PEARにいれていない場合はPEARコマンドでライブラリのインストールが必要。
以下、サンプル。このblogのURL(http://d.hatena.ne.jp/hideack/)をgoo.gl形式に短縮してみる。

<?php
require_once 'HTTP/Request2.php';

try {
    $request = new HTTP_Request2("https://www.googleapis.com/urlshortener/v1/url?key=(取得したAPIキー)", HTTP_Request2::METHOD_POST);
			
    $request->setConfig('ssl_verify_peer', false);
    $request->setHeader("Content-Type", "application/json");
    $request->setBody('{"longUrl": "http://d.hatena.ne.jp/hideack/"}');
    $response = $request->send();

    if ($response->getStatus() == 200) {
        $body = $response->getBody();
        $res = json_decode($body);

        printf("SHORT URL = %s", $res->id);
    }
    else {
        throw new Exception ("Server returned status: " .  $response->getStatus());
    }
}catch (HTTP_Request2_Exception $e) {
    echo $e->getMessage();
}catch (Exception $e) {
    echo $e->getMessage();
}
?>

これを実行すると、

% php -q test.php
SHORT URL = http://goo.gl/NDkke

となって、短縮されたAPIを取得できたことがわかる。
ちなみに、APIの利用状況はAPIキーを取得する準備の際に利用したAPIコンソールを見ることでリアルタイムに把握することができる。
f:id:hideack:20110504224723p:image