面向使用服务帐号的客户的 Java 快速入门

按照本快速入门指南中的步骤操作,大约 10 分钟后,您将获得一个简单的 Java 命令行应用,该应用使用服务帐号向零触摸注册客户 API 发出请求。

前提条件

如需运行本快速入门,您需要执行以下操作:

第 1 步:启用 Zero-Touch Enrollment API

  1. 可以使用此向导在 Google Developers Console 中创建或选择项目,并自动启用此 API。点击继续,然后点击转到凭据
  2. 您要访问哪些数据?设为应用数据
  3. 点击 Next。系统会提示您创建服务帐号。
  4. 服务帐号名称指定一个描述性名称。
  5. 记下服务帐号 ID(类似于电子邮件地址),因为您稍后会用到它。
  6. 角色设置为服务帐号 > Service Account User
  7. 点击完成以完成服务帐号的创建过程。
  8. 点击您创建的服务帐号的电子邮件地址。
  9. 点击 **密钥**。
  10. 点击 **添加密钥**,然后点击 **创建新密钥**。
  11. 对于 **密钥类型**,选择 **JSON**。
  12. 点击创建,私钥即会下载到您的计算机。
  13. 点击 **关闭**。
  14. 将文件移至工作目录,并将其重命名为 service_account_key.json

第 2 步:准备项目

如需设置 Gradle 项目,请按以下步骤操作:

  1. 运行以下命令,在工作目录中创建一个新项目:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. 将您在创建服务帐号时下载的 service_account_key.json 复制到上面创建的 src/main/resources/ 目录中。

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

apply plugin: 'java'
apply plugin: 'application'

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

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:2.2.0'
    compile 'com.google.apis:google-api-services-androiddeviceprovisioning:v1-rev20230509-2.0.0'
    compile 'com.google.auth:google-auth-library-oauth2-http:1.16.1'
    compile 'com.google.auth:google-auth-library-credentials:1.16.1'
    compile 'com.google.http-client:google-http-client:1.43.1'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
}

第 3 步:设置示例

创建一个名为 src/main/java/CustomerQuickstart.java 的文件,然后复制以下代码并保存该文件。

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androiddeviceprovisioning.v1.AndroidProvisioningPartner;
import com.google.api.services.androiddeviceprovisioning.v1.model.Company;
import com.google.api.services.androiddeviceprovisioning.v1.model.CustomerListCustomersResponse;
import com.google.api.services.androiddeviceprovisioning.v1.model.CustomerListDpcsResponse;
import com.google.api.services.androiddeviceprovisioning.v1.model.Dpc;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/** This class forms the quickstart introduction to the zero-touch enrollment customer API. */
public class CustomerQuickstart {

  // A single auth scope is used for the zero-touch enrollment customer API.
  private static final List<String> SCOPES =
      Arrays.asList("https://www.googleapis.com/auth/androidworkzerotouchemm");
  private static final String APP_NAME = "Zero-touch Enrollment Java Quickstart";

  // Global shared instances
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static HttpTransport HTTP_TRANSPORT;

  static {
    try {
      HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
      t.printStackTrace();
      System.exit(1);
    }
  }

  /**
   * Creates a GoogleCredentials object with the correct OAuth2 authorization for the service
   * account that calls the reseller API. The service endpoint invokes this method when setting up a
   * new service instance.
   *
   * @return an authorized GoogleCredentials object.
   * @throws IOException
   */
  public static GoogleCredentials authorize() throws IOException {
    // Load service account key.
    InputStream in = CustomerQuickstart.class.getResourceAsStream("/service_account_key.json");

    // Create the credential scoped to the zero-touch enrollment customer APIs.
    GoogleCredentials credential = ServiceAccountCredentials.fromStream(in).createScoped(SCOPES);
    return credential;
  }

  /**
   * Build and return an authorized zero-touch enrollment API client service. Use the service
   * endpoint to call the API methods.
   *
   * @return an authorized client service endpoint
   * @throws IOException
   */
  public static AndroidProvisioningPartner getService() throws IOException {
    GoogleCredentials credential = authorize();
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
    return new AndroidProvisioningPartner.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName(APP_NAME)
        .build();
  }

  /**
   * Runs the zero-touch enrollment quickstart app.
   *
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    // Create a zero-touch enrollment API service endpoint.
    AndroidProvisioningPartner service = getService();

    // Get the customer's account. Because a customer might have more
    // than one, limit the results to the first account found.
    AndroidProvisioningPartner.Customers.List accountRequest = service.customers().list();
    accountRequest.setPageSize(1);
    CustomerListCustomersResponse accountResponse = accountRequest.execute();
    if (accountResponse.getCustomers().isEmpty()) {
      // No accounts found for the user. Confirm the Google Account
      // that authorizes the request can access the zero-touch portal.
      System.out.println("No zero-touch enrollment account found.");
      System.exit(-1);
    }
    Company customer = accountResponse.getCustomers().get(0);
    String customerAccount = customer.getName();

    // Send an API request to list all the DPCs available using the customer account.
    AndroidProvisioningPartner.Customers.Dpcs.List request =
        service.customers().dpcs().list(customerAccount);
    CustomerListDpcsResponse response = request.execute();

    // Print out the details of each DPC.
    java.util.List<Dpc> dpcs = response.getDpcs();
    for (Dpc dpcApp : dpcs) {
      System.out.format("Name:%s  APK:%s\n", dpcApp.getDpcName(), dpcApp.getPackageName());
    }
  }
}

第 4 步:运行示例代码

请使用操作系统的帮助来运行该文件中的脚本。在 UNIX 和 Mac 计算机上,在终端中运行以下命令:

gradle -q run

备注

  • 避免与任何人共享您的 service_account_key.json 文件。请注意不要将其包含在源代码库中。您可以详细了解如何处理服务帐号密钥

了解详情