面向客户的 Java 快速入门

按照本快速入门指南中的步骤操作,在大约 10 分钟内 一个简单的 Java 命令行应用,可向零触摸事件发送请求 注册客户 API。

前提条件

如需运行本快速入门,您需要:

第 1 步:启用零触摸注册 API

  1. 使用此 向导,以在 Google Developers Console 中创建或选择项目。 系统会自动启用该 API。点击继续,然后点击前往凭据页面
  2. 在“创建凭据”页面上点击取消
  3. 在页面顶部,选择 OAuth 同意屏幕标签页。请选择一个 Email address(电子邮件地址),输入 Product name(如果尚未设置),并且 点击保存按钮。
  4. 选择凭据标签页,然后点击创建凭据。 按钮,然后选择 OAuth 客户端 ID
  5. 选择应用类型其他,然后输入名称 “快速入门”,然后点击创建 按钮。
  6. 点击确定以关闭 OAuth 客户端面板。
  7. 点击 下载 JSON
  8. 将文件移动到工作目录,并将其重命名为 client_secret.json

第 2 步:准备项目

请按照以下步骤设置 Gradle 项目:

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

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. 将您在第 1 步中下载的 client_secret.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.oauth-client:google-oauth-client-jetty:1.34.1'
}

第 3 步:设置示例

创建一个名为 src/main/java/CustomerQuickstart.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.HttpTransport;
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.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 java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/** This class forms the quickstart introduction to the zero-touch enrollemnt 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";
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".credentials/zero-touch.quickstart.json");

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

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

  /**
   * Creates a Credential object with the correct OAuth2 authorization for the user calling the
   * customer API. The service endpoint invokes this method when setting up a new service instance.
   *
   * @return an authorized Credential object.
   * @throws IOException
   */
  public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = CustomerQuickstart.class.getResourceAsStream("/client_secret.json");

    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in, "UTF-8"));

    // Ask the user to authorize the request using their Google Account
    // in their browser.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    System.out.println("Credential file saved to: " + DATA_STORE_DIR.getAbsolutePath());
    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 {
    Credential credential = authorize();
    return new AndroidProvisioningPartner.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .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

首次运行应用时,您需要授予访问权限:

  1. 应用会尝试在您的默认浏览器中打开新标签页。如果此操作失败,请从 控制台,并在浏览器中将其打开。如果您还没有登录 Google 账号, 提示登录。如果您登录了多个 Google 账号,页面会提示您选择 用于授权的账号。
  2. 点击接受
  3. 关闭浏览器标签页,应用会继续运行。

备注

  • 由于 Google API 客户端库在文件系统中存储授权数据,因此后续 也不会提示您进行授权
  • 要重置应用的授权数据,请删除 ~/.credentials/zero-touch.quickstart.json 文件,然后再次运行应用。
  • 本快速入门中的授权流程非常适合命令行应用。如需了解如何添加 授权,请参阅 OAuth 2.0 Web 服务器应用

问题排查

以下是您需要检查的一些常见事项。 <ph type="x-smartling-placeholder"></ph> 请将快速入门中的问题告诉我们,我们将努力解决此问题。

  • 确保您在授权 API 调用时使用的 Google 账号是您 零触摸注册客户账号。尝试使用以下网址登录零触摸注册门户: 请使用同一个 Google 账号测试您的访问权限。
  • 确认账号已接受最新版《服务条款》 门户网站。请参阅 客户账号

了解详情