Java 快速入門導覽課程

快速入門導覽課程說明如何設定及執行會呼叫 Google Workspace API

Google Workspace 快速入門導覽課程會使用 API 用戶端程式庫 驗證和授權流程的詳細資訊建議做法 您為自己的應用程式使用用戶端程式庫本快速入門導覽課程會使用 適合用於測試的簡易驗證方式 環境。在正式環境中,建議您瞭解 驗證與授權選擇存取認證 挑選適合您應用程式的語言版本

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

目標

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

必要條件

  • 擁有已啟用 Google Meet 的 Google Workspace 帳戶。

設定環境

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

啟用 API

您必須先在 Google Cloud 專案中啟用這些 Google API,才能使用這些 API。 您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中啟用 Google Meet API。

    啟用 API

如要使用新的 Google Cloud 專案完成本快速入門導覽課程,請設定 將自己新增為測試使用者。如果您已 為 Cloud 專案完成這個步驟,請直接跳到下一節。

  1. 在 Google Cloud 控制台中,前往「選單」圖示 > API 與服務 >「OAuth 同意畫面」

    前往 OAuth 同意畫面

  2. 在「使用者類型」部分選取「內部」,然後按一下「建立」
  3. 填寫應用程式註冊表單,然後按一下「儲存並繼續」
  4. 您現在可以略過新增範圍的步驟,然後按一下「儲存並繼續」。 日後您可以製作並使用應用程式 Google Workspace 機構,您必須將「使用者類型」變更為「外部」, 新增應用程式所需的授權範圍。

  5. 查看應用程式註冊摘要。如要修改資訊,請按一下「編輯」。如果應用程式 註冊看起來沒有問題,請按一下 [返回資訊主頁]

授權電腦版應用程式憑證

如要驗證使用者及存取應用程式中的使用者資料,您必須: 建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可用來識別 單一應用程式傳送至 Google 的 OAuth 伺服器。如果您的應用程式在多個平台上運作 您都必須為每個平台分別建立用戶端 ID。
  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 > 「API 與」「服務」 >「憑證」

    前往「憑證」

  2. 依序點選「建立憑證」>「OAuth 用戶端 ID」
  3. 依序按一下「應用程式類型」>「電腦版應用程式」
  4. 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 點選「建立」。系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
  6. 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
  7. 將下載的 JSON 檔案儲存為 credentials.json,然後移動 檔案複製到工作目錄

準備工作區

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

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

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

    meet/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'MeetQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.cloud:google-cloud-meet:0.3.0'
        implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
    }
    

設定範例

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

  2. 在您的新的 Java 檔案中加入下列程式碼:

    meet/quickstart/src/main/java/MeetQuickstart.java
    import java.awt.Desktop;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URI;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Collections;
    import java.util.List;
    
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.apps.meet.v2.CreateSpaceRequest;
    import com.google.apps.meet.v2.Space;
    import com.google.apps.meet.v2.SpacesServiceClient;
    import com.google.apps.meet.v2.SpacesServiceSettings;
    import com.google.auth.Credentials;
    import com.google.auth.oauth2.ClientId;
    import com.google.auth.oauth2.DefaultPKCEProvider;
    import com.google.auth.oauth2.TokenStore;
    import com.google.auth.oauth2.UserAuthorizer;
    
    /* class to demonstrate use of Drive files list API */
    public class MeetQuickstart {
      /**
       * Directory to store authorization tokens for this application.
       */
      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("https://www.googleapis.com/auth/meetings.space.created");
    
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      private static final String USER = "default";
    
      // Simple file-based token storage for storing oauth tokens
      private static final TokenStore TOKEN_STORE = new TokenStore() {
        private Path pathFor(String id) {
          return Paths.get(".", TOKENS_DIRECTORY_PATH, id + ".json");
        }
    
        @Override
        public String load(String id) throws IOException {
          if (!Files.exists(pathFor(id))) {
            return null;
          }
          return Files.readString(pathFor(id));
        }
    
        @Override
        public void store(String id, String token) throws IOException {
          Files.createDirectories(Paths.get(".", TOKENS_DIRECTORY_PATH));
          Files.writeString(pathFor(id), token);
        }
    
        @Override
        public void delete(String id) throws IOException {
          if (!Files.exists(pathFor(id))) {
            return;
          }
          Files.delete(pathFor(id));
        }
      };
    
      /**
       * Initialize a UserAuthorizer for local authorization.
       * 
       * @param callbackUri
       * @return
       */
      private static UserAuthorizer getAuthorizer(URI callbackUri) throws IOException {
        // Load client secrets.
        try (InputStream in = MeetQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH)) {
          if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
          }
    
          ClientId clientId = ClientId.fromStream(in);
    
          UserAuthorizer authorizer = UserAuthorizer.newBuilder()
              .setClientId(clientId)
              .setCallbackUri(callbackUri)
              .setScopes(SCOPES)
              .setPKCEProvider(new DefaultPKCEProvider() {
                // Temporary fix for https://github.com/googleapis/google-auth-library-java/issues/1373
                @Override
                public String getCodeChallenge() {
                  return super.getCodeChallenge().split("=")[0];
                }
              })
              .setTokenStore(TOKEN_STORE).build();
          return authorizer;
        }
      }
    
      /**
       * Run the OAuth2 flow for local/installed app.
       * 
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credentials getCredentials()
          throws Exception {
    
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().build();
        try {
          URI callbackUri = URI.create(receiver.getRedirectUri());
          UserAuthorizer authorizer = getAuthorizer(callbackUri);
    
          Credentials credentials = authorizer.getCredentials(USER);
          if (credentials != null) {
            return credentials;
          }
    
          URL authorizationUrl = authorizer.getAuthorizationUrl(USER, "", null);
          if (Desktop.isDesktopSupported() && 
              Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            Desktop.getDesktop().browse(authorizationUrl.toURI());
          } else {
            System.out.printf("Open the following URL to authorize access: %s\n",
                authorizationUrl.toExternalForm());
          }
    
          String code = receiver.waitForCode();
          credentials = authorizer.getAndStoreCredentialsFromCode(USER, code, callbackUri);
          return credentials;
        } finally {
          receiver.stop();
        }
      }
    
      public static void main(String... args) throws Exception {
        // Override default service settings to supply user credentials.
        Credentials credentials = getCredentials();
        SpacesServiceSettings settings = SpacesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();
    
        try (SpacesServiceClient spacesServiceClient = SpacesServiceClient.create(settings)) {
          CreateSpaceRequest request = CreateSpaceRequest.newBuilder()
              .setSpace(Space.newBuilder().build())
              .build();
          Space response = spacesServiceClient.createSpace(request);
          System.out.printf("Space created: %s\n", response.getMeetingUri());
        } catch (IOException e) {
          // TODO(developer): Handle errors
          e.printStackTrace();
        }
      }
    }

執行範例

  1. 執行範例:

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

    Java 應用程式會執行並呼叫 Google Meet API。

    授權資訊會儲存在檔案系統中,因此下次您執行範例時 這樣系統就不會提示您授權

後續步驟