Müşteriler için Java hızlı başlangıç kılavuzu

Bu hızlı başlangıç kılavuzundaki adımları uygulayın ve yaklaşık 10 dakika içinde el değmeden kayıt müşteri API'sine istekte bulunan basit bir Java komut satırı uygulamanız olsun.

Ön koşullar

Bu hızlı başlangıç kılavuzunu çalıştırmak için aşağıdakilere ihtiyacınız vardır:

  • Bir Google hesabı; el değmeden kayıt müşterisi hesabınızın üyesi. Başlayın başlıklı makaleye göz atın.
  • Java 1.7 veya sonraki bir sürüm.
  • Grad2.3 veya sonraki sürümler.
  • İnternete ve web tarayıcısına erişim.

1. Adım: El değmeden kayıt API'sini etkinleştirin

  1. Google Developers Console'da proje oluşturmak veya seçmek ve API'yi otomatik olarak etkinleştirmek için bu sihirbazı kullanın. Devam'ı ve ardından Kimlik bilgilerine git'i tıklayın.
  2. Kimlik bilgisi oluştur'da İptal'i tıklayın.
  3. Sayfanın üst kısmından OAuth izin ekranı sekmesini seçin. Bir E-posta adresi seçin, önceden ayarlanmamışsa bir Ürün adı girin ve Kaydet düğmesini tıklayın.
  4. Kimlik bilgisi sekmesini seçin, Kimlik bilgisi oluştur düğmesini tıklayın ve OAuth istemci kimliği'ni seçin.
  5. Diğer uygulama türünü seçin, "Hızlı Başlangıç" adını girin ve Oluştur düğmesini tıklayın.
  6. OAuth istemcisi panelini kapatmak için Tamam'ı tıklayın.
  7. JSON'u indir'i tıklayın.
  8. Dosyayı çalışma dizininize taşıyın ve client_secret.json olarak yeniden adlandırın.

2. Adım: Projeyi hazırlayın

Gradle projenizi oluşturmak için aşağıdaki adımları uygulayın:

  1. Çalışma dizininde yeni bir proje oluşturmak için aşağıdaki komutu çalıştırın:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. 1. adımda indirdiğiniz client_secret.json dosyasını yukarıda oluşturduğunuz src/main/resources/ dizinine kopyalayın.

  3. Varsayılan build.gradle dosyasını açın ve içeriğini aşağıdaki kodla değiştirin:

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. Adım: Örneği oluşturma

src/main/java/CustomerQuickstart.java adlı bir dosya oluşturun ve aşağıdaki kodu kopyalayıp dosyayı kaydedin.

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. Adım: Örneği çalıştırın

Komut dosyasını dosyada çalıştırmak için işletim sisteminizin yardımını kullanın. UNIX ve Mac bilgisayarlarda, terminalinizde aşağıdaki komutu çalıştırın:

gradle -q run

Uygulamayı ilk kez çalıştırdığınızda erişimi yetkilendirmeniz gerekir:

  1. Uygulama, varsayılan tarayıcınızda yeni bir sekme açmaya çalışır. Bu işlem başarısız olursa URL'yi konsoldan kopyalayıp tarayıcınızda açın. Google Hesabınızda oturum açmadıysanız giriş yapmanız istenir. Birden fazla Google Hesabı'na giriş yaptıysanız sayfada yetkilendirme için bir hesap seçmeniz istenir.
  2. Kabul et'i tıklayın.
  3. Tarayıcı sekmesini kapatın. Uygulama çalışmaya devam eder.

Notlar

  • Google API istemci kitaplığı, dosya verilerini yetkilendirme sisteminde depoladığından, sonraki başlatma işlemleri sırasında yetkilendirme istenmez.
  • Uygulamanın yetkilendirme verilerini sıfırlamak için ~/.credentials/zero-touch.quickstart.json dosyasını silin ve uygulamayı tekrar çalıştırın.
  • Bu hızlı başlangıçtaki yetkilendirme akışı, komut satırı uygulaması için idealdir. Bir web uygulamasına nasıl yetkilendirme ekleyeceğinizi öğrenmek için OAuth 2.0 Web sunucusu uygulamaları bölümüne bakın.

Sorun giderme

Kontrol etmek isteyebileceğiniz bazı yaygın konuları burada bulabilirsiniz. Hızlı başlangıç kılavuzuyla ilgili sorunu bize bildirin. Sorunu düzeltmek için çalışıyoruz.

  • API çağrılarını el değmeden kayıt müşteri hesabınızın üyesi olan Google Hesabı ile yetkilendirdiğinizden emin olun. Erişiminizi test etmek için aynı Google Hesabı'nı kullanarak el değmeden kayıt portalında oturum açmayı deneyin.
  • Hesabın portalda en son Hizmet Şartları'nı kabul ettiğini onaylayın. Müşteri hesapları sayfasını inceleyin.

Daha fazla bilgi