מדריך למתחילים ל-Java ללקוחות

פועלים לפי השלבים במדריך למתחילים. אחרי כ-10 דקות, אפליקציית שורת פקודה פשוטה של Java ששולחת בקשות דרך הארגון ממשק ה-API של רישום לקוח.

דרישות מוקדמות

כדי להפעיל את המדריך למתחילים הזה, צריך:

  • חשבון Google שחבר בלקוח שלכם בהרשמה דרך הארגון חשבון. ראו Get בתהליך.
  • Java 1.7 ומעלה.
  • Gradle 2.3 ואילך.
  • גישה לאינטרנט ולדפדפן אינטרנט.

שלב 1: מפעילים את ה-API להרשמה דרך הארגון

  1. אפשר להשתמש בקישור הזה באשף ליצירה או בחירה של פרויקט ב-Google Developers Console, להפעיל את ה-API באופן אוטומטי. לוחצים על המשך ואז על מעבר לפרטי הכניסה. .
  2. לוחצים על Cancel (ביטול) בדף Create Credentials.
  3. בחלק העליון של הדף, לוחצים על הכרטיסייה OAuth screen consent (מסך ההסכמה של OAuth). בוחרים את כתובת אימייל, מזינים את שם המוצר (אם הוא עדיין לא מוגדר). לוחצים על הלחצן שמירה.
  4. בוחרים בכרטיסייה Credentials ואז לוחצים על Create credentials. ובוחרים באפשרות OAuth Client ID (מזהה לקוח OAuth).
  5. בוחרים את סוג האפליקציה אחר ומזינים את שם האפליקציה 'מדריך למתחילים', ולוחצים על יצירה. לחצן.
  6. לוחצים על OK כדי לסגור את החלונית לקוח OAuth.
  7. לוחצים על הורדת JSON.
  8. צריך להעביר את הקובץ לספריית העבודה ולשנות את השם שלו ל-client_secret.json.

שלב 2: הכנת הפרויקט

כדי להגדיר את פרויקט Gradle, פועלים לפי השלבים הבאים:

  1. כדי ליצור פרויקט חדש בספריית העבודה, מריצים את הפקודה הבאה:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. מעתיקים את הקובץ client_secret.json שהורדתם בשלב 1 לתוך הספרייה src/main/resources/ שיצרת למעלה.

  3. פותחים את קובץ ברירת המחדל build.gradle ומחליפים את התוכן שלו הקוד הבא:

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

שלב 3: הגדרת הדוגמה

יוצרים קובץ בשם src/main/java/CustomerQuickstart.java ומעתיקים את הקוד הבא ושומרים את הקובץ.

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

שלב 4: הרצת הדוגמה

מריצים את הסקריפט שבקובץ בעזרת העזרה של מערכת ההפעלה. ב-UNIX וב-Mac מריצים את הפקודה הבאה בטרמינל:

gradle -q run

בפעם הראשונה שמפעילים את האפליקציה, צריך לתת הרשאה לגישה:

  1. האפליקציה תנסה לפתוח כרטיסייה חדשה בדפדפן ברירת המחדל. אם הפעולה נכשלת, מעתיקים את כתובת ה-URL במסוף ופותחים אותו בדפדפן. אם עדיין לא התחברתם לחשבון Google, סימן צריך להתחבר לחשבון. אם אתם מחוברים לכמה חשבונות Google, בדף תתבקשו לבחור חשבון עבור ההרשאה.
  2. לוחצים על אישור.
  3. סוגרים את הכרטיסייה בדפדפן – האפליקציה ממשיכה לפעול.

הערות

  • מכיוון שספריית הלקוח של Google API מאחסנת נתוני הרשאות במערכת הקבצים, הפעלות לא יבקשו ממך הרשאה.
  • כדי לאפס את נתוני ההרשאות של האפליקציה, מוחקים את ~/.credentials/zero-touch.quickstart.json ולהפעיל שוב את האפליקציה.
  • תהליך ההרשאה במדריך למתחילים הזה אידיאלי לאפליקציית שורת הפקודה. הוראות להוספה הרשאה לאפליקציית אינטרנט: אפליקציות שרת אינטרנט מסוג OAuth 2.0.

פתרון בעיות

הנה כמה דברים נפוצים שכדאי לבדוק. אפשר לספר לנו מה השתבש במדריך למתחילים, וננסה לפתור את הבעיה.

  • צריך לוודא שאתם מאשרים קריאות ל-API דרך אותו חשבון Google שהוא חבר ב- חשבון לקוח בהרשמה דרך הארגון. כדאי לנסות להיכנס לפורטל ההרשמה דרך הארגון באמצעות באותו חשבון Google כדי לבדוק את הגישה.
  • לאשר שהחשבון אישר את התנאים וההגבלות העדכניים של הפורטל. ראו חשבונות לקוח.

מידע נוסף