Analytics Reporting API v4 入门:适用于安装的应用的 Java 快速入门

本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。

1. 启用 API

要开始使用 Analytics Reporting API V4,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目、启用 API 以及创建凭据。

注意:要创建网络客户端 ID 或已安装的应用客户端,您需要在同意屏幕中设置产品名称。如果您尚未设置,则系统会提示您配置同意屏幕

创建凭据

  • 打开“凭据”页面
  • 点击创建凭据并选择 OAuth 客户端 ID
  • 对于应用类型请选择其他
  • 命名客户端 ID 快速入门,并点击创建

“凭据”页点击进入新创建的客户端 ID,然后点击下载 JSON,并将其另存为 client_secrets.json;在本教程的后面,您将需要用到该 JSON。

2. 安装客户端库

要安装 Google Analytics(分析)API Java 客户端,您必须下载一个包含所有 JAR 文件(您需要将这些文件提取并复制到自己的 Java 类路径中)的 ZIP 文件。

  1. 下载 Analytics Reporting API v4 Java 客户端库(打包为包含所有必需依赖关系的 ZIP 文件)。
  2. 提取该 ZIP 文件。
  3. libs 目录中的所有 JAR 文件添加到您的类路径中。
  4. google-api-services-analyticsreporting-v4-[version].jar JAR 文件添加到您的类路径中。

Java 环境详情

Eclipse

对于 Eclipse,请参阅此 StackOverflow 问题,了解有关如何将 JAR 文件添加到项目类路径中的说明。

NetBeans

对于 NetBeans,请参阅此 StackOverflow 问题,了解有关如何将 JAR 文件添加到项目类路径中的说明。

IntelliJ IDEA

对于 IntelliJ IDEA,请参阅此 StackOverflow 问题,了解有关如何将 JAR 文件添加到项目类路径中的说明。

命令行

如果您要在命令行中进行开发工作,请将以下内容添加到您的 javacjava 命令调用中:

-classpath /path/to/directory/with/unzipped/jars

3. 设置示例

您需要创建一个名为 HelloAnalyticsReporting.java 的文件,其中将包含指定的示例代码。

  • 将以下源代码复制或下载HelloAnalyticsReporting.java
  • 将先前下载的 client_secrets.json 移到示例代码所在的目录中。
  • VIEW_ID 的值替换为您要访问的数据视图的 ID。
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 java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.analyticsreporting.v4.AnalyticsreportingScopes;
import com.google.analyticsreporting.v4.Analyticsreporting;
import com.google.analyticsreporting.v4.model.ColumnHeader;
import com.google.analyticsreporting.v4.model.DateRange;
import com.google.analyticsreporting.v4.model.DateRangeValues;
import com.google.analyticsreporting.v4.model.Dimension;
import com.google.analyticsreporting.v4.model.GetReportsRequest;
import com.google.analyticsreporting.v4.model.GetReportsResponse;
import com.google.analyticsreporting.v4.model.Metric;
import com.google.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.analyticsreporting.v4.model.Report;
import com.google.analyticsreporting.v4.model.ReportRequest;
import com.google.analyticsreporting.v4.model.ReportRow;

/**
 * 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";

  // Replace with your view ID.
  private static final String VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // 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 Reporting";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      Analyticsreporting service = initializeAnalyticsReporting();

      GetReportsResponse response = getReport(service);
      printResponse(response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Initializes an authorized Analytics Reporting service object.
   *
   * @return The analytics reporting service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static Analyticsreporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

    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 authorization scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
            AnalyticsreportingScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");
    // Construct the Analytics Reporting service object.
    return new Analyticsreporting.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }

  /**
   * Query the Analytics Reporting API V4.
   * Constructs a request for the sessions for the past seven days.
   * Returns the API response.
   *
   * @param service
   * @return GetReportResponse
   * @throws IOException
   */
  private static GetReportsResponse getReport(Analyticsreporting service) throws IOException {
    // Create the DateRange object.
    DateRange dateRange = new DateRange();
    dateRange.setStartDate("7DaysAgo");
    dateRange.setEndDate("today");

    // Create the Metrics object.
    Metric sessions = new Metric()
        .setExpression("ga:sessions")
        .setAlias("sessions");

    //Create the Dimensions object.
    Dimension browser = new Dimension()
        .setName("ga:browser");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
        .setViewId(VIEW_ID)
        .setDateRanges(Arrays.asList(dateRange))
        .setDimensions(Arrays.asList(browser))
        .setMetrics(Arrays.asList(sessions));

    ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
    requests.add(request);

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest()
        .setReportRequests(requests);

    // Call the batchGet method.
    GetReportsResponse response = service.reports().batchGet(getReport).execute();

    // Return the response.
    return response;
  }

  /**
   * Parses and prints the Analytics Reporting API V4 response.
   *
   * @param response the Analytics Reporting API V4 response.
   */
  private static void printResponse(GetReportsResponse response) {

    for (Report report: response.getReports()) {
      ColumnHeader header = report.getColumnHeader();
      List<String> dimensionHeaders = header.getDimensions();
      List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
      List<ReportRow> rows = report.getData().getRows();

      if (rows == null) {
         System.out.println("No data found for " + VIEW_ID);
         return;
      }

      for (ReportRow row: rows) {
        List<String> dimensions = row.getDimensions();
        List<DateRangeValues> metrics = row.getMetrics();
        for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
          System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
        }

        for (int j = 0; j < metrics.size(); j++) {
          System.out.print("Date Range (" + j + "): ");
          DateRangeValues values = metrics.get(j);
          for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
            System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
          }
        }
      }
    }
  }
}

4. 运行示例

如果您使用的是 IDE,请确保您已将默认运行目标设为 HelloAnalytics 类。

  • 应用将在浏览器中加载授权页面。
  • 如果您尚未登录自己的 Google 帐户,那么系统会提示您登录。如果您登录了多个 Google 帐户,那么系统会提示您选择一个帐户来用于授权。

当您完成这些步骤后,示例代码就会输出给定数据视图过去 7 天内的会话数。