適用於使用服務帳戶的客戶的 Java 快速入門導覽課程

只要按照本快速入門指南中的步驟操作,約 10 分鐘內,您就能完成一個簡單的 Java 指令列應用程式,該應用程式會使用服務帳戶向零接觸註冊客戶 API 提出要求。

必要條件

如要執行本快速入門導覽課程,您需要:

  • 與零接觸註冊機制客戶連結的服務帳戶 讓他們使用服務帳戶請參閱取得 已開始
  • Java 1.7 以上版本。
  • Gradle 2.3 以上版本
  • 連上網際網路和網路瀏覽器。

步驟 1:啟用零接觸註冊機制 API

  1. 請使用此 精靈在 Google Developers Console 中建立或選取專案,並且 系統會自動啟用 API依序點選「繼續」和「前往憑證」
  2. 將「您要存取哪些資料?」設為「應用程式資料」
  3. 按一下「繼續」,系統會提示您建立服務 讓他們使用服務帳戶
  4. 為「服務帳戶名稱」設定描述性的名稱。
  5. 記下「服務帳戶 ID」 (形式為電子郵件地址), 以便稍後使用
  6. 角色設為服務帳戶 >服務帳戶使用者
  7. 按一下「Done」(完成),即完成建立服務帳戶。
  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 檔案。請注意 但不要加到原始碼存放區如需進一步說明,請參閱: 處理服務帳戶密鑰

瞭解詳情