Java 快速入门

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。

Google Workspace 快速入门使用 API 客户端库来处理身份验证和授权流程的某些细节。我们建议您为自己的应用使用客户端库。本快速入门使用适合测试环境的简化身份验证方法。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您的应用的访问凭据

创建一个向 Google Chat API 发出请求的 Java 命令行应用。

目标

  • 设置环境。
  • 设置示例。
  • 运行示例。

前提条件

设置环境

如需完成本快速入门,请设置您的环境。

启用 API

在使用 Google API 之前,您需要先在 Google Cloud 项目中启用这些 API。您可以在单个 Google Cloud 项目中启用一个或多个 API。
  • 在 Google Cloud 控制台中,启用 Google Chat API。

    启用 API

如果您使用新的 Google Cloud 项目完成本快速入门,请配置 OAuth 同意屏幕。如果您已为 Cloud 项目完成此步骤,请跳至下一部分。

  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > > 品牌

    前往“品牌”页面

  2. 如果您已配置 ,则可以在品牌受众群体数据访问中配置以下 OAuth 同意屏幕设置。如果您看到一条消息,其中显示 尚未配置,请点击开始
    1. 应用信息下的应用名称中,输入应用的名称。
    2. 用户支持电子邮件中,选择一个支持电子邮件地址,以便用户在对其同意问题有疑问时与您联系。
    3. 点击下一步
    4. 观众下,选择内部
    5. 点击下一步
    6. 联系信息下,输入一个电子邮件地址,以便您接收有关项目的任何更改的通知。
    7. 点击下一步
    8. 完成下方,查看 Google API 服务用户数据政策,如果您同意,请选择我同意 Google API 服务:用户数据政策
    9. 点击继续
    10. 点击创建
  3. 目前,您可以跳过添加镜重。 今后,如果您创建的应用供 Google Workspace 组织之外的用户使用,则必须将用户类型更改为外部。然后,添加您的应用所需的授权范围。如需了解详情,请参阅完整的配置 OAuth 同意指南。

为桌面应用授权凭据

如需对最终用户进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台分别创建客户端 ID。
  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > > 客户端

    前往“客户”页面

  2. 点击创建客户端
  3. 依次点击应用类型 > 桌面应用
  4. 名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
  5. 点击创建

    新创建的凭据会显示在“OAuth 2.0 客户端 ID”下。

  6. 将下载的 JSON 文件另存为 credentials.json,然后将该文件移至您的工作目录。

配置 Google Chat 应用

如需调用 Google Chat API,您必须配置 Google Chat 应用。对于任何写入请求,Google Chat 都会使用以下信息在界面中归因 Google Chat 应用。

  1. 在 Google Cloud 控制台中,前往 Chat API 配置页面:

    前往 Chat API 配置页面

  2. 应用信息下,输入以下信息:

    1. 应用名称字段中,输入 Chat API quickstart app
    2. 头像网址字段中,输入 https://developers.google.com/chat/images/quickstart-app-avatar.png
    3. 说明字段中,输入 Quickstart for calling the Chat API
  3. 互动功能下,将启用互动功能切换开关切换到关闭位置,以停用 Chat 应用的互动功能。

  4. 点击保存

准备工作区

  1. 在工作目录中,创建一个新的项目结构:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. src/main/resources/ 目录中,复制您之前下载的 credentials.json 文件。

  3. 打开默认的 build.gradle 文件,并将其内容替换为以下代码:

    chat/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'ChatQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0'
        implementation 'com.google.api-client:google-api-client:1.33.0'
        implementation 'com.google.api.grpc:proto-google-cloud-chat-v1:0.8.0'
        implementation 'com.google.api:gax:2.48.1'
        implementation 'com.google.cloud:google-cloud-chat:0.1.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
    }

设置示例

  1. src/main/java/ 目录中,创建一个新 Java 文件,其名称与 build.gradle 文件中的 mainClassName 值匹配。

  2. 在新 Java 文件中添加以下代码:

    chat/quickstart/src/main/java/ChatQuickstart.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.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.Credentials;
    import com.google.auth.oauth2.AccessToken;
    import com.google.auth.oauth2.UserCredentials;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.ChatServiceSettings;
    import com.google.chat.v1.ListSpacesRequest;
    import com.google.chat.v1.Space;
    import com.google.protobuf.util.JsonFormat;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Collections;
    import java.util.Date;
    import java.util.List;
    
    /* class to demonstrate use of Google Chat API spaces list API */
    public class ChatQuickstart {
      /** 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/chat.spaces.readonly");
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      /**
       * 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 {
        // Load client secrets.
        InputStream credentialsFileInputStream =
            ChatQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (credentialsFileInputStream == null) {
          throw new FileNotFoundException("Credentials file resource not found.");
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialsFileInputStream));
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
                // Set these two options to generate refresh token alongside access token.
                .setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
    
        // Authorize.
        Credential credential =
            new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
        // Build and return an authorized Credential object
        AccessToken accessToken =
            new AccessToken(
                credential.getAccessToken(),
                new Date(
                    // put the actual expiry date of access token here
                    System.currentTimeMillis()));
        return UserCredentials.newBuilder()
            .setAccessToken(accessToken)
            .setRefreshToken(credential.getRefreshToken())
            .setClientId(clientSecrets.getInstalled().getClientId())
            .setClientSecret(clientSecrets.getInstalled().getClientSecret())
            .build();
      }
    
      public static void main(String... args) throws Exception {
        // Override default service settings to supply user credentials.
        Credentials credentials = getCredentials();
    
        // Create the ChatServiceSettings with the credentials
        ChatServiceSettings chatServiceSettings =
            ChatServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
                .build();
    
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create(chatServiceSettings)) {
          ListSpacesRequest request =
              ListSpacesRequest.newBuilder()
                  // Filter spaces by space type (SPACE or GROUP_CHAT or
                  // DIRECT_MESSAGE).
                  .setFilter("spaceType = \"SPACE\"")
                  .build();
    
          // Iterate over results and resolve additional pages automatically.
          for (Space response : chatServiceClient.listSpaces(request).iterateAll()) {
            System.out.println(JsonFormat.printer().print(response));
          }
        }
      }
    }

运行示例

  1. 运行示例:

    gradle run
    
  1. 首次运行该示例时,系统会提示您授予访问权限:
    1. 如果您尚未登录 Google 账号,请在系统提示时登录。如果您登录了多个账号,请选择一个账号用于授权。
    2. 点击接受

    您的 Java 应用运行并调用 Google Chat API。

    授权信息会存储在文件系统中,因此当您下次运行示例代码时,系统不会提示您进行授权。

后续步骤