Hello Analytics API: Guide de démarrage rapide Java pour les applications installées

Ce tutoriel décrit les étapes requises pour accéder à un compte Google Analytics, interroger les API Analytics, gérer les réponses de l'API et générer les résultats. Ce tutoriel utilise l'API Core Reporting v3.0, l'API Management v3.0 et OAuth2.0.

Étape 1: Activez l'API Analytics

Pour commencer à utiliser l'API Google Analytics, vous devez d'abord utiliser l'outil de configuration, qui vous guide tout au long de la création d'un projet dans la console Google APIs, de l'activation de l'API et de la création d'identifiants.

Créer un ID client

Depuis la page "Identifiants" :

  1. Cliquez sur Créer des identifiants, puis sélectionnez ID client OAuth.
  2. Sélectionnez Autre pour TYPE D'APPLICATION.
  3. Attribuez un nom à l'identifiant.
  4. Cliquez sur Créer.

Sélectionnez les identifiants que vous venez de créer, puis cliquez sur Download JSON (Télécharger JSON). Enregistrez le fichier téléchargé sous le nom client_secrets.json. Vous en aurez besoin dans la suite du tutoriel.

Étape 2: Installez la bibliothèque cliente Google

Pour installer le client Java de l'API Google Analytics, vous devez télécharger un fichier ZIP contenant tous les fichiers JAR que vous devez extraire et copier dans votre classpath Java.

  1. Téléchargez la bibliothèque cliente Java Google Analytics, fournie sous forme de fichier ZIP avec toutes les dépendances requises.
  2. Extrayez le fichier ZIP.
  3. Ajoutez tous les fichiers JAR du répertoire libs à votre classpath.
  4. Ajoutez le fichier JAR google-api-services-analytics-v3-[version].jar au chemin de classe.

Étape 3: Configurer l'exemple

Vous devez créer un seul fichier nommé HelloAnalytics.java, qui contiendra l'exemple de code donné.

  1. Copiez ou téléchargez le code source suivant dans HelloAnalytics.java.
  2. Déplacez le fichier client_secrets.json précédemment téléchargé dans le même répertoire que l'exemple de code.
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");
    }
  }
}

Étape 4: Exécutez l'exemple

Après avoir activé l'API Analytics, installé la bibliothèque cliente des API Google pour Java et configuré l'exemple de code source, celui-ci est prêt à être exécuté.

Si vous utilisez un IDE, assurez-vous qu'une cible d'exécution par défaut est définie sur la classe HelloAnalytics.

  1. L'application charge la page d'autorisation dans un navigateur.
  2. Si vous n'êtes pas déjà connecté à votre compte Google, vous serez invité à le faire. Si vous êtes connecté à plusieurs comptes Google, vous êtes invité à sélectionner un compte à utiliser pour l'autorisation.

Lorsque vous avez terminé ces étapes, l'exemple génère le nom de la première vue (profil) Google Analytics de l'utilisateur autorisé, ainsi que le nombre de sessions au cours des sept derniers jours.

Avec l'objet de service Analytics autorisé, vous pouvez désormais exécuter n'importe quel exemple de code disponible dans la documentation de référence de l'API Management. Par exemple, vous pouvez essayer de modifier le code pour utiliser la méthode accountSummaries.list.