Hướng dẫn nhanh về Java dành cho đại lý

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ẽ có 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 đại lý đă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 có:

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. Đặt mục 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 dịch vụ tài khoản.
  4. Đặt tên mô tả cho Tên tài khoản dịch vụ.
  5. Ghi lại Mã tài khoản dịch vụ (mã này trông giống một địa chỉ email) vì bạn sẽ để sau này sử dụng.
  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 của tài khoản dịch vụ bạn đã tạo.
  9. Nhấp vào **Khoá**.
  10. Nhấp vào **Thêm khoá**, rồi nhấp vào **Tạo khoá mới**.
  11. Đối với **Loại khoá**, hãy chọn **JSON**.
  12. Nhấp vào Tạo rồi tải khoá riêng tư xuống máy tính.
  13. Nhấp vào **Đóng**.
  14. Di chuyển tệp vào thư mục đang làm việc rồi đổi tên tệp service_account_key.json.
  1. Mở cổng thiết lập tự động. Bạn có thể cần phải đăng nhập.
  2. Nhấp vào Dịch vụ tài khoản.
  3. Nhấp vào Liên kết tài khoản dịch vụ.
  4. Đặt Địa chỉ email thành địa chỉ của tài khoản dịch vụ bạn đã tạo.
  5. Nhấp vào Liên kết tài khoản dịch vụ để sử dụng tài khoản dịch vụ mà bạn thiết lập tự động tài khoản đăng ký của bạn.

Bước 3: 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 service_account_key.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 = 'ResellerQuickstart'
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile 'com.google.api-client:google-api-client:1.30.11'
        compile 'com.google.apis:google-api-services-androiddeviceprovisioning:+'
        compile 'com.google.oauth-client:google-oauth-client-jetty:+'
    }
    

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

Tạo một tệp có tên src/main/java/ResellerQuickstart.java rồi sao chép trong sau đó mã và lưu tệp. Chèn đối tác đại lý của riêng bạn ID làm giá trị cho PARTNER_ID (dòng đầu tiên của ứng dụng).

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.jackson2.JacksonFactory;
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.ListCustomersResponse;
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
 * reseller API.
 */
public class ResellerQuickstart {

  // TODO: replace this with your partner reseller ID.
  private static long PARTNER_ID = 11036885;

  // Use a single scope for the all methods in the reseller API.
  private static final List<String> SCOPES =
      Arrays.asList("https://www.googleapis.com/auth/androidworkprovisioning");
  private static final String APP_NAME = "Zero-touch Reseller Java Quickstart";

  // Global shared instances.
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
  private static HttpTransport HTTP_TRANSPORT;

  static {
    try {
      HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
      t.printStackTrace();
      System.exit(1);
    }
  }

  /**
   * Creates a Credential 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 Credential object.
   * @throws IOException
   */
  public static Credential authorize() throws IOException {
      // Load the service account key from the JSON file.
      InputStream in =
          ResellerQuickstart.class.getResourceAsStream("/service_account_key.json");

      // Create the credential scoped to the zero-touch enrollemnt
      // reseller APIs.
      GoogleCredential credential = GoogleCredential
         .fromStream(in)
         .createScoped(SCOPES);
      return credential;
  }

  /**
   * Builds and returns 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();

    // Send an API request to list all our customers.
    AndroidProvisioningPartner.Partners.Customers.List request =
          service.partners().customers().list(PARTNER_ID);
    ListCustomersResponse response = request.execute();

    // Print out the details of each customer.
    if (response.getCustomers() != null) {
      java.util.List<Company> customers = response.getCustomers();
      for (Company customer : customers) {
          System.out.format("Name:%s  ID:%d\n",
                customer.getCompanyName(),
                customer.getCompanyId());
      }
    } else {
      System.out.println("No customers found");
    }
  }
}

Mã nhận dạng đối tác

Lệnh gọi API thường cần mã đối tác của đại lý làm đối số. Để tìm mã đối tác từ cổng thiết lập tự động, hãy làm theo các bước dưới đây:

  1. Mở cổng. Bạn có thể cần phải đăng nhập.
  2. Nhấp vào Dịch vụ tài khoản.
  3. Sao chép mã đối tác trong dòng Mã đại lý của bạn.

Bước 5: 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

Khắc phục sự cố

Hãy cho chúng tôi biết vấn đề trong phần bắt đầu nhanh và chúng tôi sẽ tìm cách khắc phục vấn đề. Để tìm hiểu cách tính năng tự động đăng ký sử dụng tài khoản dịch vụ để uỷ quyền cho các lệnh gọi API, hãy đọc Uỷ quyền.

Tìm hiểu thêm