Apresentação da API Google Analytics: guia de início rápido do Java para aplicativos instalados

Este tutorial mostra as etapas necessárias para acessar uma conta do Google Analytics, consultar as APIs do Google Analytics, lidar com as respostas da API e gerar os resultados. A API Core Reporting v3.0, a API Management v3.0 e o OAuth2.0 são usados neste tutorial.

Etapa 1: ativar a API Google Analytics

Para começar a usar a API Google Analytics, primeiro use a ferramenta de configuração, que fornece orientações para você criar um projeto no console de APIs do Google, ativar a API e criar credenciais.

Criar um Client-ID

Na página "Credenciais":

  1. Clique em Criar credenciais e selecione OAuth Client-ID.
  2. Selecione Outro em TIPO DE APLICATIVO.
  3. Defina um nome para a credencial.
  4. Clique em Criar.

Selecione a credencial que você acabou de criar e clique em Fazer o download do JSON. Salve o arquivo como client_secrets.json. Você precisará dele mais adiante no tutorial.

Etapa 2: Instalar a biblioteca de cliente do Google

Para instalar o cliente Java da Google Analytics API, você precisa fazer o download de um arquivo ZIP com todos os jars necessários para extrair e copiar para seu caminho de classe Java.

  1. Faça o download da biblioteca cliente de Java do Google Analytics, que está agrupada como um arquivo ZIP com todas as dependências necessárias.
  2. Extraia o arquivo ZIP.
  3. Adicione todos os JARs no diretório libs ao seu caminho de classe.
  4. Adicione o jar google-api-services-analytics-v3-[version].jar ao seu caminho de classe.

Etapa 3: configurar a amostra

Você precisará criar um único arquivo chamado HelloAnalytics.java, que conterá o código de amostra fornecido.

  1. Copie ou faça o download do código-fonte a seguir para HelloAnalytics.java.
  2. Mova o client_secrets.json salvo anteriormente para o mesmo diretório que o exemplo de código.
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");
    }
  }
}

Etapa 4: executar a amostra

Depois que você ativar a API Analytics, instalar a biblioteca cliente das APIs do Google para Java e configurar o código-fonte da amostra, ela está pronta para ser executada.

Se você estiver usando um ambiente de desenvolvimento integrado, verifique se tem uma execução padrão definida para a classe HelloAnalytics.

  1. O aplicativo carregará a página de autorização em um navegador.
  2. Se você ainda não tiver feito login na sua Conta do Google, receberá uma solicitação. Se você estiver conectado a várias Contas do Google, terá que selecionar uma para usar na autorização.

Quando você concluir essas etapas, a amostra gerará o nome da primeira vista (perfil) do Google Analytics do usuário autorizado, além do número de sessões dos últimos sete dias.

Com o objeto de serviço autorizado do Google Analytics, agora você pode executar qualquer uma das amostras de código nos documentos de referência da API Management. Por exemplo, tente alterar o código para usar o método accountSummaries.list.