Panduan memulai Java bagi pelanggan yang menggunakan akun layanan

Ikuti langkah-langkah dalam panduan memulai ini, dan dalam waktu sekitar 10 menit, Anda telah memiliki aplikasi command line Java sederhana yang membuat permintaan ke API pelanggan pendaftaran zero-touch menggunakan akun layanan.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

Langkah 1: Aktifkan API pendaftaran zero-touch

  1. Gunakan wizard ini untuk membuat atau memilih project di Google Developers Console dan otomatis mengaktifkan API. Klik Continue, lalu Go to credentials .
  2. Setel Data apa yang akan Anda akses? ke Data aplikasi.
  3. Klik Berikutnya. Anda akan diminta untuk membuat akun layanan.
  4. Beri nama deskriptif untuk Nama akun layanan.
  5. Catat ID akun layanan (formatnya seperti alamat email) karena Anda akan menggunakannya nanti.
  6. Tetapkan Role ke Service Accounts > Service Account User.
  7. Klik Selesai untuk menyelesaikan pembuatan akun layanan.
  8. Klik alamat email untuk akun layanan yang dibuat.
  9. Klik **Kunci**.
  10. Klik **Add key**, lalu klik **Create new key**.
  11. Untuk **Key type**, pilih **JSON**.
  12. Klik Create dan kunci pribadi akan didownload ke komputer Anda.
  13. Klik **Tutup**.
  14. Pindahkan file ke direktori kerja Anda dan ganti namanya menjadi service_account_key.json.

Langkah 2: Siapkan project

Ikuti langkah-langkah di bawah ini untuk menyiapkan project Gradle Anda:

  1. Jalankan perintah berikut untuk membuat project baru di direktori kerja:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. Salin service_account_key.json yang Anda download saat membuat akun layanan ke dalam direktori src/main/resources/ yang Anda buat di atas.

  3. Buka file build.gradle default dan ganti kontennya dengan kode berikut:

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

Langkah 3: Siapkan contoh file

Buat file bernama src/main/java/CustomerQuickstart.java dan salin dalam kode berikut dan simpan file tersebut.

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

Langkah 4: Jalankan contoh aplikasi

Gunakan bantuan sistem operasi untuk menjalankan skrip dalam file. Di komputer UNIX dan Mac, jalankan perintah di bawah ini di terminal Anda:

gradle -q run

Catatan

  • Jangan membagikan file service_account_key.json Anda kepada siapa pun. Berhati-hatilah untuk tidak menyertakannya dalam repositori kode sumber. Anda dapat membaca saran selengkapnya tentang menangani rahasia akun layanan.

Mempelajari lebih lanjut