Java 快速入門導覽課程

快速入門導覽課程說明如何設定及執行呼叫 Google Workspace API 的應用程式。

Google Workspace 快速入門導覽課程會使用 API 用戶端程式庫,處理驗證和授權流程的一些細節。建議您針對自己的應用程式使用用戶端程式庫。本快速入門導覽課程採用適用於測試環境的簡化驗證方式。對於實際工作環境,建議您先瞭解驗證和授權,再選擇應用程式適用的存取憑證

建立 Java 指令列應用程式,向 Google Keep API 提出要求。

目標

  • 設定環境。
  • 設定範例。
  • 執行範例。

必要條件

  • 擁有已啟用 Google Keep 的 Google 帳戶。

設定環境

如要完成本快速入門導覽課程,請設定環境。

啟用 API

使用 Google API 前,請先在 Google Cloud 專案中啟用這些 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中啟用 Google Keep API。

    啟用 API

建立服務帳戶

服務帳戶是應用程式 (而非使用者) 使用的特殊帳戶。您可以使用服務帳戶來存取機器人帳戶的資料或執行操作,或是代表 Google Workspace 或 Cloud Identity 使用者存取資料。詳情請參閱「瞭解服務帳戶」。

Google Cloud 控制台

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 按一下「建立服務帳戶」
  3. 填寫服務帳戶詳細資料,然後按一下「建立並繼續」
  4. 選用:將角色指派給服務帳戶,即可授予 Google Cloud 專案資源的存取權。詳情請參閱「授予、變更及撤銷資源的存取權」。
  5. 點選「繼續」
  6. 選用:輸入可透過這個服務帳戶管理及執行動作的使用者或群組。詳情請參閱「管理服務帳戶模擬功能」。
  7. 按一下 [完成]。記下服務帳戶的電子郵件地址。

gcloud CLI

  1. 建立服務帳戶:
    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME \
      --display-name="SERVICE_ACCOUNT_NAME"
  2. 選用:將角色指派給服務帳戶,即可授予 Google Cloud 專案資源的存取權。詳情請參閱「授予、變更及撤銷資源的存取權」。

建立服務帳戶的憑證

您必須取得公開/私密金鑰組的憑證,程式碼會使用這些憑證,在應用程式中授權服務帳戶動作。
  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 選取服務帳戶。
  3. 依序按一下「金鑰」>「新增金鑰」>「建立新的金鑰」
  4. 選取「JSON」,然後按一下「建立」

    系統就會為您產生一組新的公開/私密金鑰,並以新檔案的形式下載至您的機器。將下載的 JSON 檔案儲存為 credentials.json,並儲存在工作目錄中。這個檔案是這組金鑰的唯一副本。如要瞭解如何安全儲存金鑰,請參閱管理服務帳戶金鑰

  5. 按一下「關閉」

為服務帳戶設定全網域委派功能

如要代表 Google Workspace 機構使用者呼叫 API,則必須透過超級管理員帳戶,在 Google Workspace 管理控制台中,授予您的服務帳戶全網域授權委派權限。詳情請參閱「將全網域授權委派給服務帳戶」。
  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 選取服務帳戶。
  3. 按一下 [顯示進階設定]
  4. 在「全網域委派」下方,找出服務帳戶的「用戶端 ID」。按一下「複製」,將用戶端 ID 值複製到剪貼簿。
  5. 如果您具備相關 Google Workspace 帳戶的超級管理員存取權,請按一下「查看 Google Workspace 管理控制台」,然後使用超級管理員使用者帳戶登入,並繼續執行下列步驟。

    如果您不具備相關 Google Workspace 帳戶的超級管理員存取權,請與該帳戶的超級管理員聯絡,並將服務帳戶的用戶端 ID 和 OAuth 範圍清單傳送給對方,以便他們在管理控制台中完成下列步驟。

    1. 在 Google 管理控制台中,依序點選「選單」圖示 >「安全性」>「存取權與資料控制」>「API 控制項」

      前往「API 控制項」

    2. 按一下「管理全網域委派設定」
    3. 按一下 [Add new] (新增)
    4. 在「用戶端 ID」欄位中,貼上先前複製的用戶端 ID。
    5. 在「OAuth 範圍」欄位中,輸入應用程式所需範圍的清單 (以半形逗號分隔)。這與您設定 OAuth 同意畫面時定義的範圍相同。
    6. 按一下「授權」。

準備工作區

  1. 在工作目錄中,建立新的專案結構:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. src/main/resources/ 目錄中,複製先前下載的 credentials.json 檔案。

  3. 開啟預設的 build.gradle 檔案,並將內容替換為以下程式碼:

      apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'KeepQuickstart'
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    version = '1.0'
    
    sourceCompatibility = 1.8
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.api-client:google-api-client:1.23.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
        implementation 'com.google.apis:google-api-services-keep:v1-rev20210528-1.31.0'
    }
    

設定範例

  1. src/main/java/ 目錄中,使用與 build.gradle 檔案中 mainClassName 值相符的名稱建立新的 Java 檔案。

  2. 在新 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.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.keep.v1.Keep;
    import com.google.api.services.keep.v1.model.Note;
    import com.google.api.services.keep.v1.model.Section;
    import com.google.api.services.keep.v1.model.TextContent;
    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 KeepQuickstart {
    
      private static final String APPLICATION_NAME = "Google Keep API Java Quickstart";
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    
      /**
       * Global instance of the scopes required by this quickstart. If modifying these scopes, delete
       * your previously saved tokens/ folder.
       */
      private static final List<String> KEEP_SCOPES =
          Collections.singletonList("https://www.googleapis.com/auth/keep");
    
      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
       */
      private static Credential getOAuthCredentials(final NetHttpTransport HTTP_TRANSPORT)
          throws IOException {
        // Load client secrets.
        InputStream in = KeepQuickstart.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, KEEP_SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File("tokens")))
                .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();
        Keep service =
            new Keep.Builder(HTTP_TRANSPORT, JSON_FACTORY, getOAuthCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();
    
        Section noteBody =
            new Section().setText(new TextContent().setText("Finish preparations by tomorrow!"));
        Note newNote = new Note().setTitle("Customer call next week").setBody(noteBody);
    
        // Creates a new text note.
        service.notes().create(newNote).execute();
      }
    }
    
    

執行範例

  1. 執行範例:

    gradle run
    
  1. 首次執行範例時,系統會提示您授予存取權:
    1. 如果您尚未登入 Google 帳戶,請在系統提示時登入。如果您登入了多個帳戶,請選取一個用於授權的帳戶。
    2. 然後點選 [Accept]

    您的 Java 應用程式會執行並呼叫 Google Keep API。

    授權資訊會儲存在檔案系統中,因此下次您執行程式碼範例時,系統不會提示您取得授權。

後續步驟