適用於客戶的 Java 快速入門導覽課程

請按照本快速入門指南所述的步驟操作,而且在大約 10 分鐘後,您將會使用簡單的 Java 指令列應用程式,向零接觸註冊客戶 API 發出要求。

必備條件

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

  • 您的 Google 帳戶是零接觸註冊機制客戶帳戶的成員。請參閱開始使用
  • Java 1.7 以上版本。
  • Gradle 2.3 以上版本
  • 連線至網際網路和網路瀏覽器。

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

  1. 使用這個精靈在 Google Developers Console 中建立或選取專案,然後自動啟用 API。依序點選「繼續」和「前往憑證」
  2. 按一下「建立憑證」上的「取消」
  3. 選取頁面頂端的「OAuth 同意畫面」分頁標籤。選取「電子郵件地址」,輸入「產品名稱」 (如果尚未設定),然後按一下「儲存」按鈕。
  4. 選取「憑證」分頁標籤,按一下「建立憑證」按鈕,然後選取「OAuth 用戶端 ID」
  5. 選取應用程式類型「Other」,輸入「快速入門導覽課程」名稱,然後按一下「建立」按鈕。
  6. 按一下「OK」關閉「OAuth 用戶端」面板。
  7. 按一下 「Download JSON」(下載 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. 然後點選 [Accept]
  3. 關閉瀏覽器分頁,應用程式會繼續執行。

Notes

  • Google API 用戶端程式庫會在檔案系統中儲存授權資料,因此後續啟動並不會啟動授權。
  • 如要重設應用程式的授權資料,請刪除 ~/.credentials/zero-touch.quickstart.json 檔案,然後再次執行應用程式。
  • 本快速入門導覽課程中的授權流程非常適合指令列應用程式。如要瞭解如何新增授權給網頁應用程式,請參閱 OAuth 2.0 網路伺服器應用程式

疑難排解

以下是一些需要檢查的常見事項。 透過快速入門導覽課程 告訴我們錯誤所在,我們會設法加以修正。

  • 請確認您用於授權 API 呼叫的 Google 帳戶與您零接觸註冊機制客戶帳戶的成員相同。請嘗試使用同一個 Google 帳戶登入零接觸註冊機制入口網站,藉此測試存取權。
  • 確認帳戶在入口網站中已接受最新的《服務條款》。請參閱「 客戶帳戶」。

瞭解詳情