Hướng dẫn nhanh về Java cho khách hàng

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.

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

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

  • Tài khoản Google là một thành viên của 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. Nhấp vào Hủy trên thông tin đăng nhập Tạo.
  3. Ở đầu trang, hãy chọn thẻ Màn hình xin phép bằng OAuth. Chọn Địa chỉ email, nhập Tên sản phẩm nếu bạn chưa đặt và nhấp vào nút Lưu.
  4. Chọn thẻ Thông tin xác thực, nhấp vào nút Tạo thông tin xác thực rồi chọn Mã ứng dụng khách OAuth.
  5. Chọn loại ứng dụng Other, nhập tên "Quickstart", rồi nhấp vào nút Create (Tạo).
  6. Nhấp vào OK để loại bỏ bảng Ứng dụng OAuth.
  7. Nhấp vào Tải xuống JSON.
  8. Di chuyển tệp vào thư mục đang làm việc và đổi tên client_secret.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 tệp client_secret.json mà bạn đã tải xuống ở Bước 1 vào thư mục src/main/resources/ 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.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.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());
    }
  }
}

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

Lần đầu tiên chạy ứng dụng, bạn cần cấp quyền truy cập:

  1. Ứng dụng sẽ tìm cách mở một thẻ mới trong trình duyệt mặc định. Nếu không thành công, hãy sao chép URL từ bảng điều khiển rồi mở trong trình duyệt. Nếu chưa đăng nhập vào Tài khoản Google của mình, bạn sẽ được nhắc đăng nhập. Nếu bạn đã đăng nhập vào nhiều tài khoản Google, trang sẽ nhắc bạn chọn một tài khoản để ủy quyền.
  2. Nhấp vào Chấp nhận.
  3. Đóng tab trình duyệt—ứng dụng sẽ tiếp tục chạy.

Ghi chú

  • Vì thư viện ứng dụng Google API lưu trữ dữ liệu ủy quyền trên hệ thống tệp, nên các lần khởi chạy tiếp theo sẽ không nhắc bạn ủy quyền.
  • Để đặt lại dữ liệu ủy quyền của ứng dụng, hãy xóa tệp ~/.credentials/zero-touch.quickstart.json rồi chạy lại ứng dụng.
  • Quy trình ủy quyền trong khởi động nhanh này lý tưởng cho ứng dụng dòng lệnh. Để tìm hiểu cách thêm ủy quyền vào ứng dụng web, hãy xem ứng dụng máy chủ Web OAuth 2.0.

Khắc phục sự cố

Dưới đây là một số điều phổ biến bạn sẽ muốn kiểm tra. Hãy cho chúng tôi biết bạn gặp vấn đề gì khi bắt đầu nhanh và chúng tôi sẽ tìm cách khắc phục.

  • Kiểm tra để đảm bảo rằng bạn ủy quyền cho các lệnh gọi API bằng cùng một Tài khoản Google dùng cho tài khoản khách hàng đăng ký thiết lập tự động. Hãy thử đăng nhập vào cổng thiết lập tự động bằng cách sử dụng cùng một Tài khoản Google để kiểm tra quyền truy cập của bạn.
  • Xác nhận rằng tài khoản đã chấp nhận Điều khoản dịch vụ mới nhất trong cổng thông tin. Xem Tài khoản khách hàng.

Tìm hiểu thêm