面向客户的 Java 快速入门

按照此快速入门指南中的步骤操作,并在大约 10 分钟内构建一个简单的 Java 命令行应用,并向零触摸注册 API 发出请求。

前提条件

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

  • Google 帐号,也就是您的零触摸注册客户帐号的成员。请参阅使用入门
  • Java 1.7 或更高版本。
  • Gradle 2.3 或更高版本
  • 能够访问互联网和网络浏览器。

第 1 步:启用 Zero-Touch Enrollment API

  1. 可以使用此向导在 Google Developers Console 中创建或选择项目,并自动启用此 API。点击继续,然后点击转到凭据
  2. 点击“创建凭据”上的取消
  3. 在页面顶部,选择 OAuth 同意屏幕标签页。选择电子邮件地址,输入产品名称(如果尚未设置),然后点击保存按钮。
  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 文件,然后重新运行应用。
  • 本快速入门中的授权流程非常适合命令行应用。如需了解如何向 Web 应用添加授权,请参阅 OAuth 2.0 Web 服务器应用

问题排查

以下是您需要检查的一些常见事项。 请 将快速入门中存在的问题告诉我们,我们将努力解决该问题。

  • 确保您授权的 API 调用与您的零触摸注册客户帐号中的成员帐号所用的 Google 帐号相同。请尝试使用同一 Google 帐号登录零触摸注册门户,以测试您的访问权限。
  • 确认相关帐号已在门户中接受最新的服务条款。请参阅 客户帐号

了解详情