哈囉 Analytics Reporting API v4:已安裝應用程式的 Java 快速入門導覽課程

本教學課程會逐步介紹存取 Analytics Reporting API v4 的必要步驟。

1. 啟用 API

如要開始使用 Analytics Reporting API v4,您必須先使用設定工具,這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

注意:若要建立網路用戶端 ID 或已安裝的應用程式用戶端,您必須在同意畫面中設定產品名稱。如果尚未完成設定同意畫面,系統會提醒您。

建立憑證

  • 開啟「Credentials」(憑證) 頁面
  • 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
  • 在「應用程式類型」部分,選取「其他」
  • 將用戶端 ID 命名為 quickstart,然後按一下「Create」

憑證頁面中,點選新建立的用戶端 ID,然後點選「下載 JSON」並儲存為 client_secrets.json;稍後在教學課程中會用到這組 ID。

2. 安裝用戶端程式庫

若要安裝 Google Analytics API Java 用戶端,您必須下載 ZIP 檔案,當中包含所有要擷取並複製到 Java 類別路徑的 jar 檔案。

  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 帳戶,系統會要求選取一個帳戶進行授權。

完成上述步驟後,樣本就會針對指定的資料檢視輸出過去七天的工作階段數。