[Android] Google URL 短縮 API を Android から呼び出してみました

| トラックバック(0) |

Google の URL 短縮 API が(2011年1月10日に)公開されたので、早速、Android から呼び出してみました。

 

公式サイト

 

API 概要

API としては、Labs のステータスですが、短縮 <=> 展開の両方をサポートしています。

短縮は POST、展開は GET メソッドで、どちらもパラメータは、JSON 形式です。

リクエストに API Key を取得・設定しておくと、1日の上限リクエスト回数は、100万回となります。

apikey.png

 

サンプルコード

以下、「http://www.adakoda.com/」を、Google URL 短縮 API を呼び出し、

短縮した結果のURL「http://goo.gl/sGdK」を得るためのサンプルコードです。

 

String apiUri = "https://www.googleapis.com/urlshortener/v1/url";
// 以下の API Key を取得したものに置き換える(省略可)
String apiKey = "";
String postUrl = ""; // POST用URL文字列
// 短縮元URL文字列
String longUrl = "http://www.adakoda.com/";
// パラメーターに日本語を含む場合は下記のようにエスケープしてください
// Uri.Builder tmpUriBuilder = new Uri.Builder();
// tmpUriBuilder.path("http://www.google.co.jp/search");
// tmpUriBuilder.appendQueryParameter("q", Uri.encode("みっくみく"));
// longUrl = Uri.decode(tmpUriBuilder.build().toString());
// POST用URL文字列作成
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.path(apiUri);
uriBuilder.appendQueryParameter("key", apiKey); // APIキー推奨
postUrl = Uri.decode(uriBuilder.build().toString());
try {
    // リクエスト作成
    HttpPost httpPost = new HttpPost(postUrl);
    httpPost.setHeader("Content-type", "application/json");
    JSONObject jsonRequest = new JSONObject();
    jsonRequest.put("longUrl", longUrl);
    StringEntity stringEntity = new StringEntity(jsonRequest.toString());
    httpPost.setEntity(stringEntity);
    // リクエスト発行
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        // 結果の取得
        String entity = EntityUtils.toString(httpResponse.getEntity());
        JSONObject jsonEntity = new JSONObject(entity);
        if (jsonEntity != null) {
            // 短縮URL結果 (このサンプルの場合、「http://goo.gl/sGdK」)
            String shortUrl = jsonEntity.optString("id");
            Log.v("id", shortUrl);
            Toast.makeText(this, shortUrl, Toast.LENGTH_LONG).show();
        }
    }
} catch (IOException e) {
} catch (JSONException e) {
}

 

実行結果

result.png

トラックバック(0)

トラックバックURL: http://mt.adakoda.com/mt-tb.cgi/517

2016年8月

  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31