API de Hello Analytics: Guía de inicio rápido de Java para aplicaciones instaladas

En este instructivo, se explican los pasos necesarios para acceder a una cuenta de Google Analytics, consultar las APIs de Analytics, manejar las respuestas de la API y generar los resultados. En este instructivo, se usan la API de Core Reporting v3.0, la API de Management v3.0 y OAuth2.0.

Paso 1: Habilita la API de Analytics

Para comenzar a usar la API de Google Analytics, primero debes utilizar la herramienta de configuración, que te guiará para crear un proyecto en la Consola de APIs de Google, habilitar la API y crear credenciales.

Crea un ID de cliente

En la página Credenciales, haz lo siguiente:

  1. Haz clic en Crear credenciales y selecciona ID de cliente de OAuth.
  2. En TIPO DE APLICACIÓN, selecciona Otro.
  3. Asigna un nombre a la credencial.
  4. Haz clic en Crear.

Selecciona la credencial que acabas de crear y haz clic en Descargar JSON. Guarda el archivo descargado como client_secrets.json; lo necesitarás más adelante en el instructivo.

Paso 2: Instala la biblioteca cliente de Google

Para instalar el cliente de Java de la API de Google Analytics, debes descargar un archivo ZIP que contenga todos los archivos jar que necesitas extraer y copiar en tu ruta de clase de Java.

  1. Descarga la biblioteca cliente de Google Analytics para Java, que se incluye como un archivo ZIP con todas las dependencias necesarias.
  2. Extraiga el archivo ZIP.
  3. Agrega todos los archivos JAR del directorio libs a tu ruta de clase.
  4. Agrega el jar google-api-services-analytics-v3-[version].jar a la ruta de clase.

Paso 3: Configura la muestra

Deberás crear un solo archivo llamado HelloAnalytics.java, que contendrá el código de muestra proporcionado.

  1. Copia o descarga el siguiente código fuente en HelloAnalytics.java.
  2. Mueve el client_secrets.json descargado previamente dentro del mismo directorio que el código de muestra.
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.javanet.NetHttpTransport;
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.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * A simple example of how to access the Google Analytics API.
 */
public class HelloAnalytics {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloAnalytics.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // The directory where the user's credentials will be stored.
  private static final File DATA_STORE_DIR = new File(
      System.getProperty("user.home"), ".store/hello_analytics");

  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();
      String profile = getFirstProfileId(analytics);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Analytics initializeAnalytics() throws Exception {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloAnalytics.class
            .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all auth scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
        AnalyticsScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }

  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No properties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}

Paso 4: Ejecuta la muestra

Después de habilitar la API de Analytics, instala la biblioteca cliente de las APIs de Google para Java y configura el código fuente de muestra que la muestra está lista para ejecutarse.

Si usas un IDE, asegúrate de tener un objetivo de ejecución predeterminado establecido en la clase HelloAnalytics.

  1. La aplicación cargará la página de autorización en un navegador.
  2. Si aún no accediste a tu Cuenta de Google, se te pedirá que lo hagas. Si accediste a varias Cuentas de Google, se te pedirá que selecciones una cuenta para usar en la autorización.

Cuando termines estos pasos, la muestra mostrará el nombre de la primera vista (perfil) de Google Analytics del usuario autorizado y la cantidad de sesiones de los últimos siete días.

Con el objeto de servicio autorizado de Analytics, ahora puedes ejecutar cualquiera de las muestras de código que se encuentran en los documentos de referencia de la API de Management. Por ejemplo, podrías intentar cambiar el código para usar el método accountSummaries.list.