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 bắt đầu nhanh này và sau khoảng 10 phút, bạn sẽ một ứng dụng dòng lệnh Java đơn giản giúp đưa ra các yêu cầu đến thiết bị tự động API khách hàng đăng ký.

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

Để chạy quy trình bắt đầu nhanh này, bạn cần:

  • Tài khoản Google là thành viên của khách hàng thiết lập tự động tài khoản. Xem phần Tải đã bắt đầu.
  • Java 1.7 trở lên.
  • Gradle 2.3 trở lên.
  • Truy cập vào Internet và trình duyệt web.

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

  1. Sử dụng này để tạo hoặc chọn 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 phần thông tin đăng nhập
  2. Nhấp vào Huỷ trên phần Tạo thông tin xác thực.
  3. Ở đầu trang, hãy chọn thẻ Màn hình xin phép bằng OAuth. Chọn một Địa chỉ email, nhập Tên sản phẩm nếu chưa đặt, và nhấp vào nút Lưu.
  4. Chọn thẻ Credentials (Thông tin đăng nhập), nhấp vào Create credentials (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 Khác, rồi nhập tên "Bắt đầu nhanh" rồi nhấp vào nút Tạo .
  6. Nhấp vào OK để đóng bảng điều khiển ứng dụng OAuth.
  7. Nhấp vào Tải tệp JSON xuống.
  8. Di chuyển tệp vào thư mục đang làm việc rồi đổi tên tệp client_secret.json.

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

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

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

    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/ mà bạn đã tạo ở trên.

  3. Mở tệp build.gradle mặc định rồi thay 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 src/main/java/CustomerQuickstart.java rồi sao chép trong sau đó mã 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 tính năng trợ giúp của hệ điều hành để chạy tập lệnh trong tệp. Trên UNIX và Mac máy tính, hãy chạy lệnh bên dưới trong cửa sổ dòng lệnh của bạn:

gradle -q run

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

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

Ghi chú

  • Vì thư viện ứng dụng API của Google lưu trữ dữ liệu uỷ quyền trên hệ thống tệp, nên các lần chạy ứng dụng không nhắc bạn về việc uỷ quyền.
  • Để đặt lại dữ liệu uỷ quyền của ứng dụng, hãy xoá ~/.credentials/zero-touch.quickstart.json rồi chạy lại ứng dụng.
  • Quy trình uỷ quyền trong phần khởi động nhanh này là lựa chọn lý tưởng cho ứng dụng dòng lệnh. Để tìm hiểu cách thêm cho phép một ứ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ểm phổ biến mà bạn nên kiểm tra. Hãy cho chúng tôi biết lỗi bằng tính năng bắt đầu nhanh và chúng tôi sẽ tìm cách khắc phục.

  • Kiểm tra để chắc chắn rằng bạn đang cho phép thực hiện lệnh gọi API bằng cùng một Tài khoản Google là thành viên của tài khoản khách hàng 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ùng một Tài khoản Google để kiểm tra quyền truy cập.
  • 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 dịch vụ. Xem Tài khoản khách hàng.

Tìm hiểu thêm