Java クイックスタート

みるくあいらんどっ! > 和訳 > google関係 > Drive API > api > v3 > クイックスタート


  • この記事は、Google Drive™ APIに関する記事を和訳したものです。
  • 原文: Java Quickstart
  • 元記事のライセンスは CC-BYで、この和訳記事のライセンスは CC-BYです。
  • 自己責任でご利用ください。
  • 和訳した時期は 2019年6月ころです。

Drive APIにリクエストを行う単純な Javaコマンドラインアプリケーションを作成するには、このページの残りの部分で説明されている手順を完了します。

前提条件

このクイックスタートを実行するには、以下の前提条件を必要とします:

  • Java 1.7以上
  • Gradle 2.3以上
  • Google Driveが有効である Googleアカウント

Step 1: Drive APIをオンにする

新しい Cloud Platform projectを作成するためにこのボタンをクリックし、Drive APIを自動的に有効にします:

Drive APIを有効にする

ダイアログが表示されたら、DOWNLOAD CLIENT CONFIGURATIONをクリックし、あなたの作業ディレクトリにファイル credentials.json を保存します。

Step 2: プロジェクトを準備する

  1. あなたの作業ディレクトリにて、新しいプロジェクト構造を作成するために次のコマンドを実行します:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. 作成した src/main/resources/ ディレクトリに、Step 1でダウンロードした credentials.jsonファイルをコピーします。

  3. デフォルトの build.gradleファイルを開き、そのコンテンツを次のコードに置換します:

drive/quickstart/build.gradle
apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'DriveQuickstart'
sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:1.23.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
    compile 'com.google.apis:google-api-services-drive:v3-rev110-1.23.0'
}

Step 3: サンプルをセットアップする

次のファイル名およびコードを伴うファイルを src/main/java/フォルダ内に作成します。

drive/quickstart/src/main/java/DriveQuickstart.java
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class DriveQuickstart {
    private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Print the names and IDs for up to 10 files.
        FileList result = service.files().list()
                .setPageSize(10)
                .setFields("nextPageToken, files(id, name)")
                .execute();
        List<File> files = result.getFiles();
        if (files == null || files.isEmpty()) {
            System.out.println("No files found.");
        } else {
            System.out.println("Files:");
            for (File file : files) {
                System.out.printf("%s (%s)\n", file.getName(), file.getId());
            }
        }
    }
}

Step 4: サンプルを実行する

次のコマンドを用いてクイックスタートをビルドし、実行します:

gradle run

サンプルを初めて実行するとき、アクセスを承認するよう求められるでしょう:

  1. サンプルは、あなたのデフォルトブラウザにて新しいウインドウあるいはタブを開こうとするでしょう。 もしこれが失敗したならば、コンソールから URLをコピーし、手動であなたのブラウザにてそれを開きます。

    もし、まだあなたの Googleアカウントにログインしていなければ、ログインを求められるでしょう。 もし、複数の Googleアカウントにログインしているならば、認証のために使用する 1つのアカウントを選択するよう求められるでしょう。

  2. Acceptボタンをクリックします。
  3. サンプルは自動的に進行するでしょう、そして、ウインドウ/タブを閉じても良いです。

ノート

  • 認証情報は、ファイルシステム上に格納されるので、以降の実行では認証を求められないでしょう。
  • この例の認証フローは、コマンドラインアプリケーションのためにデザインされています。 ウェブアプリケーションにて認証を実行する方法については、Using OAuth 2.0 for Web Server Applicationsを参照してください。

参考文献

トラブルシューティング

このセクションでは、このクイックスタートを実行しようとしたときに遭遇するかもしれない、幾つかの一般的な問題について説明し、可能な解決策を提案します。

This app isn't verified.

機密性の高いユーザデータへのアクセスを提供するスコープをリクエストしている場合、ユーザに表示される OAuth同意画面に、警告 "This app isn't verified" が表示されるかもしれません。 これらのアプリケーションは、その警告および他の制限を取り除くための検証プロセスを、最終的には通過しなければなりません。 開発段階では、Advanced > Go to {Project Name} (unsafe) をクリックすることによって、この警告を追加し続けることができます。