LoginSignup
11
11

More than 5 years have passed since last update.

JavaアプリケーションからGoogle URL Shortener APIを使用する

Last updated at Posted at 2015-12-26

概要

Javaアプリケーションより、Google URL Shortener APIを使用するサンプルアプリケーションです。認証にAPIキーとサービスアカウントによる2つの方法を試しました。

環境

  • Windows7 (64bit)
  • Java 1.8.0_65

参考

準備

まず、Google Developers Consoleにアクセスしてキーの作成とAPIの有効化を行います。

プロジェクトの作成

テスト用のプロジェクトを作成します。(既存にテストで使用できるプロジェクトがあればそれを使ってもかまいません)
プロジェクトを作成をクリックしプロジェクト名を入力します。

a01.png

今回はMy-API-Test Porjectとしました。
プロジェクトが作成されるとダッシュボードに移動します。

a02.png

APIの有効化

URL Shortener APIを有効化します。

a03.png

a04.png

a05.png

OAuth同意画面の設定画面

プロジェクトのOAuth同意画面の設定がまだの場合は、最初に設定を行っておく必要があります。
新規に作成したプロジェクトなので設定を行いました。サービス名に適当な名前を入力して保存します。

a07.png

キーの作成

APIキーとサービスアカウントキーを作成します。

APIキー

a08.png

名前を付けて作成するとAPIキーが発行されます。

a10.png

サービスアカウントキー

a11.png

名前を付けキーのタイプにP12を選択して作成します。
続いてキーファイルのダウンロードが始まります。

a12.png

サービスアカウントのメールアドレスを確認します。

a13.png

モザイクにしていますが、メールアドレス欄に記載されている文字列がサービスアカウントのメールアドレスです。

a14.png

アプリケーションの開発

使用するライブラリ

pom.xmlに下記の依存関係を追加します。

pom.xml
<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-urlshortener</artifactId>
  <version>v1-rev41-1.21.0</version>
</dependency>

resourcesフォルダの作成

src/main/resourcesフォルダを作成しここにダウンロードしたP12ファイルを配置します。

APIキーを使うサンプル

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.urlshortener.Urlshortener;
import com.google.api.services.urlshortener.UrlshortenerRequestInitializer;
import com.google.api.services.urlshortener.model.Url;

/**
 * API KEY サンプル
 */
public class Sample2 {

  //アプリケーション名 (任意)
  private static final String APPLICATION_NAME = "urlshortener-application-example/1.0";

  private static final String API_KEY = "取得したAPIキーの値";

  public static void main(String[] args) {
    Sample2 sample = new Sample2();
    String longUrl = "http://qiita.com/rubytomato@github";

    try {
      UrlshortenerRequestInitializer initializer = sample.authorize();
      Urlshortener service = sample.getService(initializer);
      Url shortUrl = sample.getShortUrl(service, longUrl);
      //getId()値が短縮URLです
      System.out.println(shortUrl.getId());
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  private Url getShortUrl(Urlshortener service, String longUrl) throws Exception {
    System.out.println("getShortUrl in");

    Url url = new Url().setLongUrl(longUrl);
    Url result = service.url().insert(url).execute();

    return result;
  }

  private UrlshortenerRequestInitializer authorize() throws Exception {
    System.out.println("authorize in");

    return new UrlshortenerRequestInitializer(API_KEY);
  }

  private Urlshortener getService(UrlshortenerRequestInitializer initializer) throws Exception {
    System.out.println("service in");

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    Urlshortener service = new Urlshortener.Builder(httpTransport, jsonFactory, null)
      .setUrlshortenerRequestInitializer(initializer)
      .setApplicationName(APPLICATION_NAME)
      .build();

    return service;
  }

}

サービスアカウントを使うサンプル

import java.io.File;
import java.util.Set;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.urlshortener.Urlshortener;
import com.google.api.services.urlshortener.UrlshortenerScopes;
import com.google.api.services.urlshortener.model.Url;

/**
 * サービスアカウントキー サンプル
 */
public class Sample3 {

  //アプリケーション名 (任意)
  private static final String APPLICATION_NAME = "urlshortener-application-example/1.0";

  private static final String ACCOUNT_ID = "サービスアカウントのメールアドレス";
  private static final File P12FILE = new File("src/main/resources/ダウンロードしたp12ファイル");

  //認証スコープ
  private static final Set<String> SCOPES = UrlshortenerScopes.all();

  public static void main(String[] args) {
    Sample3 sample = new Sample3();
    String longUrl = "http://qiita.com/rubytomato@github";

    try {
      Credential credential = sample.authorize();
      Urlshortener service = sample.getService(credential);
      Url shortUrl = sample.getShortUrl(service, longUrl);
      //getId()値が短縮URLです
      System.out.println(shortUrl.getId());
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  private Url getShortUrl(Urlshortener service, String longUrl) throws Exception {
    System.out.println("getShortUrl in");

    Url url = new Url().setLongUrl(longUrl);
    Url result = service.url().insert(url).execute();

    return result;
  }

  private Credential authorize() throws Exception {
    System.out.println("authorize in");

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(ACCOUNT_ID)
      .setServiceAccountPrivateKeyFromP12File(P12FILE)
      .setServiceAccountScopes(SCOPES)
      .build();

    boolean ret = credential.refreshToken();
    System.out.println("refreshToken:" + ret);

    // debug dump
    if (credential != null) {
      String accessToken = credential.getAccessToken();
      Long expires = credential.getExpiresInSeconds();
      System.out.println("AccessToken:" + accessToken);
      System.out.println("expires:" + expires);
    }

    return credential;
  }

  /**
   * 保存していたアクセストークンからcredentialを生成することができます 
   */
  private GoogleCredential makeCredential(String accessToken) {
    System.out.println("makeCredential in");

    GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);

    if (credential != null) {
      accessToken = credential.getAccessToken();
      Long expires = credential.getExpiresInSeconds();
      System.out.println("AccessToken:" + accessToken);
      System.out.println("expires:" + expires);
    }

    return credential;
  }

  private Urlshortener getService(Credential credential) throws Exception {
    System.out.println("service in");

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    Urlshortener service = new Urlshortener.Builder(httpTransport, jsonFactory, credential)
    .setApplicationName(APPLICATION_NAME)
    .build();

    return service;
  }

}
11
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11