歡迎使用 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;後續步驟將會用到。

2. 安裝用戶端程式庫

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

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

完成這些步驟後,範例會輸出最近七天內的指定資料檢視數量。