Hướng dẫn nhanh về Java cho khách hàng sử dụng tài khoản dịch vụ

Hãy làm theo các bước trong hướng dẫn nhanh này và trong khoảng 10 phút, bạn có một ứng dụng dòng lệnh Java đơn giản giúp thực hiện các yêu cầu đối với API khách hàng thiết lập tự động bằng tài khoản dịch vụ.

Điều kiện tiên quyết

Để chạy tính năng khởi động nhanh này, bạn cần:

  • Một tài khoản dịch vụ được liên kết với tài khoản khách hàng thiết lập tự động. Xem phần Bắt đầu.
  • Java 1.7 trở lên.
  • Gradle 2.3 trở lên.
  • Truy cập Internet và trình duyệt web.

Bước 1: Bật API thiết lập tự động

  1. Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, sau đó nhấp vào Chuyển đến thông tin đăng nhập.
  2. Đặt Bạn sẽ truy cập dữ liệu nào? thành Dữ liệu ứng dụng.
  3. Nhấp vào Tiếp theo. Bạn sẽ được nhắc tạo một tài khoản dịch vụ.
  4. Đặt tên mô tả cho Tên tài khoản dịch vụ.
  5. Hãy lưu ý đến Mã tài khoản dịch vụ (có vẻ giống như địa chỉ email) vì bạn sẽ sử dụng thông tin này sau.
  6. Đặt Vai trò thành Tài khoản dịch vụ > Người dùng tài khoản dịch vụ.
  7. Nhấp vào Xong để hoàn tất việc tạo tài khoản dịch vụ.
  8. Nhấp vào địa chỉ email cho tài khoản dịch vụ mà bạn đã tạo.
  9. Nhấp vào **Khóa**.
  10. Nhấp vào **Thêm khoá**, sau đó nhấp vào **Tạo khoá mới**.
  11. Đối với **Loại khóa**, hãy chọn **JSON**.
  12. Nhấp vào Tạo và khóa cá nhân sẽ được tải xuống máy tính của bạn.
  13. Nhấp vào **Đóng**.
  14. Di chuyển tệp vào thư mục đang làm việc và đổi tên service_account_key.json.

Bước 2: Chuẩn bị dự án

Hãy làm theo các bước dưới đây để thiết lập dự án Gradle:

  1. Chạy lệnh sau để tạo một dự án mới trong thư mục đang hoạt động:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. Sao chép service_account_key.json mà bạn đã tải xuống khi tạo tài khoản dịch vụ vào thư mục src/main/resources/ mà bạn đã tạo ở trên.

  3. Mở tệp build.gradle mặc định và thay thế nội dung của tệp đó bằng mã sau:

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

Bước 3: Thiết lập mẫu

Tạo một tệp có tên là src/main/java/CustomerQuickstart.java rồi sao chép vào mã sau và lưu tệp đó.

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

Bước 4: Chạy mẫu

Sử dụng trợ giúp của hệ điều hành để chạy tập lệnh trong tệp. Trên máy tính UNIX và Mac, hãy chạy lệnh bên dưới trong thiết bị đầu cuối của bạn:

gradle -q run

Ghi chú

Tìm hiểu thêm