Guía de inicio rápido de Java para clientes

Sigue los pasos de esta guía de inicio rápido y, en unos 10 minutos, tendrás una app de línea de comandos de Java simple que realiza solicitudes a la API del cliente de inscripción automática.

Requisitos previos

Para ejecutar esta guía de inicio rápido, necesitas lo siguiente:

Paso 1: Activa la API de inscripción automática

  1. Usa este asistente para crear o seleccionar un proyecto en Google Developers Console y activar automáticamente la API. Haz clic en Continuar y, luego, en Ir a credenciales.
  2. En Crear credenciales, haga clic en Cancelar.
  3. En la parte superior de la página, seleccione la pestaña OAuth consent screen. Selecciona una Dirección de correo electrónico, ingresa un Nombre del producto si todavía no lo configuraste y haz clic en el botón Guardar.
  4. Selecciona la pestaña Credenciales, haz clic en el botón Crear credenciales y selecciona ID de cliente de OAuth.
  5. Selecciona el tipo de aplicación Otro, ingresa el nombre "Guía de inicio rápido" y haz clic en el botón Crear.
  6. Haz clic en Aceptar para descartar el panel Cliente OAuth.
  7. Haz clic en Descargar JSON.
  8. Mueve el archivo a tu directorio de trabajo y cámbiale el nombre a client_secret.json.

Paso 2: Prepara el proyecto

Sigue los pasos que se indican a continuación para configurar tu proyecto de Gradle:

  1. Ejecuta el siguiente comando para crear un proyecto nuevo en el directorio de trabajo:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. Copia el archivo client_secret.json que descargaste en el Paso 1 en el directorio src/main/resources/ que creaste antes.

  3. Abre el archivo build.gradle predeterminado y reemplaza su contenido por el siguiente código:

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

Paso 3: Configura la muestra

Crea un archivo llamado src/main/java/CustomerQuickstart.java, cópialo en el siguiente código y guarda el archivo.

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

Paso 4: Ejecuta la muestra

Usa la ayuda de tu sistema operativo para ejecutar la secuencia de comandos en el archivo. En computadoras UNIX y Mac, ejecuta el siguiente comando en la terminal:

gradle -q run

La primera vez que ejecutas la app, debes autorizar el acceso:

  1. La app intenta abrir una pestaña nueva en el navegador predeterminado. Si esto falla, copia la URL de la consola y ábrela en tu navegador. Si aún no accediste a tu Cuenta de Google, se te solicitará que lo hagas. Si accediste a varias Cuentas de Google, la página te pedirá que selecciones una para la autorización.
  2. Haz clic en Aceptar.
  3. Cierra la pestaña del navegador. La app continúa ejecutándose.

Notas

  • Debido a que la biblioteca cliente de la API de Google almacena datos de autorización en el sistema de archivos, los inicios posteriores no te solicitan autorización.
  • Para restablecer los datos de autorización de la app, borra el archivo ~/.credentials/zero-touch.quickstart.json y vuelve a ejecutar la app.
  • El flujo de autorización de esta guía de inicio rápido es ideal para una app de línea de comandos. Si quieres obtener información sobre cómo agregar autorización a una app web, consulta Aplicaciones del servidor web de OAuth 2.0.

Solución de problemas

Estas son algunas cosas que deberías revisar. Cuéntanos qué salió mal con la guía de inicio rápido, y trabajaremos para solucionarlo.

  • Verifica que estés autorizando llamadas a la API con la misma Cuenta de Google que forma parte de tu cuenta de cliente de inscripción automática. Intenta acceder al portal de inscripción automática con la misma Cuenta de Google para probar el acceso.
  • Confirma que la cuenta haya aceptado las Condiciones del Servicio más recientes en el portal. Consulta el artículo Cuentas de clientes.

Más información