Java-Kurzanleitung für Kunden, die ein Dienstkonto verwenden

Führen Sie die Schritte in dieser Kurzanleitung aus. In etwa 10 Minuten haben Sie eine einfache Java-Befehlszeile, die über ein Dienstkonto Anfragen an die Zero-Touch-Registrierungs-API des Kunden sendet.

Voraussetzungen

Zum Ausführen dieser Kurzanleitung benötigen Sie Folgendes:

  • Ein Dienstkonto, das mit Ihrem Zero-Touch-Registrierungskundenkonto verknüpft ist. Siehe Jetzt starten.
  • Java 1.7 oder höher.
  • Gradle 2.3 oder höher
  • Zugriff auf das Internet und einen Webbrowser.

Schritt 1: API für die Zero-Touch-Registrierung aktivieren

  1. Mit diesem Assistenten können Sie ein Projekt in der Google Developers Console erstellen oder auswählen und die API automatisch aktivieren. Klicken Sie auf Weiter und dann auf Anmeldedaten aufrufen.
  2. Setzen Sie Auf welche Daten werden Sie zugreifen? auf Anwendungsdaten.
  3. Klicken Sie auf Weiter. Sie werden aufgefordert, ein Dienstkonto zu erstellen.
  4. Geben Sie einen aussagekräftigen Namen für Dienstkontoname ein.
  5. Notieren Sie sich die Dienstkonto-ID (diese sieht wie eine E-Mail-Adresse aus), da Sie sie später verwenden.
  6. Setzen Sie die Rolle auf Dienstkonten > Dienstkontonutzer.
  7. Klicken Sie auf Fertig, um das Erstellen des Dienstkontos abzuschließen.
  8. Klicken Sie auf die E-Mail-Adresse des von Ihnen erstellten Dienstkontos.
  9. Klicken Sie auf **Schlüssel**.
  10. Klicken Sie auf **Schlüssel hinzufügen** und dann auf **Neuen Schlüssel erstellen**.
  11. Wählen Sie für **Schlüsseltyp** die Option **JSON** aus.
  12. Klicken Sie auf Erstellen und der private Schlüssel wird auf Ihren Computer heruntergeladen.
  13. Klicken Sie auf **Schließen**.
  14. Verschieben Sie die Datei in Ihr Arbeitsverzeichnis und benennen Sie sie in service_account_key.json um.

Schritt 2: Projekt vorbereiten

So richten Sie ein Gradle-Projekt ein:

  1. Führen Sie den folgenden Befehl aus, um ein neues Projekt im Arbeitsverzeichnis zu erstellen:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. Kopieren Sie die service_account_key.json, die Sie beim Erstellen Ihres Dienstkontos heruntergeladen haben, in das oben erstellte Verzeichnis src/main/resources/.

  3. Öffnen Sie die Standarddatei build.gradle und ersetzen Sie den Inhalt durch den folgenden Code:

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'
}

Schritt 3: Beispiel einrichten

Erstellen Sie eine Datei mit dem Namen src/main/java/CustomerQuickstart.java, kopieren Sie den folgenden Code und speichern Sie die Datei.

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());
    }
  }
}

Schritt 4: Beispiel ausführen

Verwenden Sie die Hilfe Ihres Betriebssystems zum Ausführen des Skripts in der Datei. Führen Sie auf UNIX- und Mac-Computern den folgenden Befehl in Ihrem Terminal aus:

gradle -q run

Hinweise

Weitere Informationen