Java 快速入門

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

快速入門指南會說明如何設定及執行呼叫 Google Workspace API 的應用程式。本快速入門導覽課程會使用簡化的驗證方法,適用於測試環境。在正式環境中,建議您先瞭解驗證和授權,再選擇適合應用程式的存取憑證

本快速入門指南會使用 Google Workspace 建議的 API 用戶端程式庫,處理驗證和授權流程的部分詳細資料。

目標

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

必要條件

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

設定環境

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

啟用 API

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

    啟用 API

如果您使用新的 Google Cloud 專案完成這項快速入門導覽課程,請設定 OAuth 同意畫面。如果已為 Cloud 專案完成這個步驟,請跳至下一節。

  1. 在 Google Cloud 控制台中,依序前往「選單」 > >「品牌」

    前往「品牌宣傳」

  2. 如果您已設定 ,可以在「品牌」、「目標對象」和「資料存取權」中設定下列 OAuth 同意畫面設定。如果看到「尚未設定」 訊息,請按一下「開始使用」
    1. 在「App Information」(應用程式資訊) 下方的「App name」(應用程式名稱) 欄位中,輸入應用程式名稱。
    2. 在「使用者支援電子郵件」中,選擇支援電子郵件地址,方便使用者在同意聲明方面有任何疑問時與您聯絡。
    3. 點選 [下一步]
    4. 在「觀眾」下方,選取「內部」
    5. 點選 [下一步]
    6. 在「聯絡資訊」下方,輸入可接收專案異動通知的電子郵件地址
    7. 點選 [下一步]
    8. 在「完成」下方,詳閱《Google API 服務:使用者資料政策》,然後選取「我同意《Google API 服務:使用者資料政策》」
    9. 按一下 [繼續]。
    10. 按一下「Create」(建立)。
  3. 目前可以略過新增範圍。 日後為 Google Workspace 機構以外的使用者建立應用程式時,請務必將「使用者類型」變更為「外部」。然後新增應用程式需要的授權範圍。詳情請參閱完整的「設定 OAuth 同意畫面」指南。

授權電腦應用程式的憑證

如要在應用程式中驗證使用者身分並存取使用者資料,您需要建立一或多個 OAuth 2.0 用戶端 ID。Google 的 OAuth 伺服器會使用用戶端 ID 來識別個別應用程式。如果您的應用程式在多個平台上執行,則必須為每個平台分別建立用戶端 ID。
  1. 前往 Google Cloud 控制台,依序點選「選單」圖示 > >「用戶端」

    前往「客戶」

  2. 按一下「建立用戶端」
  3. 依序點選「應用程式類型」>「電腦應用程式」
  4. 在「Name」(名稱) 欄位中,輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 Client IDs」(OAuth 2.0 用戶端 ID) 下方。

  6. 將下載的 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/ 目錄中,建立新的 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。

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

後續步驟