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

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

前提条件

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

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

  1. 使用此 向导,以在 Google Developers Console 中创建或选择项目。 系统会自动启用该 API。点击继续,然后点击前往凭据页面
  2. 您要访问哪些数据?设置为应用数据
  3. 点击下一步。系统应该会提示您创建 Service 。
  4. 服务账号名称提供一个描述性名称。
  5. 记下服务账号 ID(看起来像是电子邮件地址),因为您将 稍后使用。
  6. 角色设置为服务账号 >Service Account User
  7. 点击完成以完成服务账号的创建过程。
  8. 点击您创建的服务账号的电子邮件地址。
  9. 点击 **Keys**。
  10. 点击 **Add key**,然后点击 **Create new key**。
  11. 对于 **密钥类型**,选择 **JSON**。
  12. 点击创建,私钥便会下载到您的计算机。
  13. 点击 **Close**。
  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 文件。请注意 请勿将其包含在源代码库中您可以访问 处理服务账号密钥

了解详情