Web アプリから Google の URL 短縮サービスを使って、
URL を短くすることができます。
Google URL Shortener API
https://developers.google.com/url-shortener/
サービスを有効化する
画面左の Google API Console をクリック
Services -> URL Shorener API を ON に切り替えて利用規約に同意する
API キーを取得する
画面左のメニューから API Access をクリック
Simple API Access の API Key に描かれている文字列が API キー
URL を短くする
Web アプリケーションから以下のような HTTP リクエストを送信すると、
短縮された URL を含むレスポンスが帰ってきます。
データは送受信ともに JSON 形式です。
リクエスト
POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json
{"longUrl": "http://www.google.com/", "key": "APIキー"}
レスポンスボディ
{
"kind": "urlshortener#url",
"id": "http://goo.gl/fbsS",
"longUrl": "http://www.google.com/"
}
Go 言語のサンプルです。通信は okalib を使っています。
// 短縮URLを取得する
key := GOOGLE_API_KEY
longUrl := Join("http://", HOSTNAME, "/runtime?game_key=", completeKey.Encode())
requestBody := Join(`{"key":"`, key, `","longUrl":"`, longUrl, `"}`)
params := make(map[string]string, 1)
params["Content-Type"] = "application/json"
response := Request(this.c, "POST", "https://www.googleapis.com/urlshortener/v1/url", params, requestBody)
responseBody := make([]byte, response.ContentLength)
_, err = response.Body.Read(responseBody)
Check(this.c, err)
result := make(map[string]string, 3)
err = json.Unmarshal(responseBody, &result)
Check(this.c, err)


0 件のコメント:
コメントを投稿