本教程详细介绍了访问 Google Analytics(分析)帐号、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0、Management API v3.0 和 OAuth2.0。
第 1 步:启用 Google Analytics(分析)API
要开始使用 Google Analytics(分析)API,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目,启用 API 以及创建凭据。
创建客户端 ID
- 打开服务帐号页。如果看到相关提示,请选择项目。
- 点击创建服务帐号。
- 在创建服务帐号窗口中,键入服务帐号的名称,然后选择提供新的私钥。如果您希望将 Google Workspace 全网域权限授予该服务帐号,另请选中启用 Google Workspace 全网域委派功能。然后点击保存。
您的新公钥/私钥对已生成并下载到您的计算机;该密钥仅此一份,您负责安全存储该密钥。
将服务帐号添加到 Google Analytics(分析)帐号中
新建服务帐户的电子邮件地址为 <projectId>-<uniqueId>@developer.gserviceaccount.com
,可用于向您想通过该 API 访问的 Google Analytics(分析)帐户添加用户。就本教程涵盖的内容而言,只需阅读和分析权限即可。
第 2 步:安装 Google 客户端库
要安装 Google Analytics(分析)API Java 客户端,您必须下载一个包含所有 JAR 文件(您需要将这些文件提取并复制到自己的 Java 类路径中)的 ZIP 文件。
- 下载 Google Analytics(分析)Java 客户端库(打包为包含所有必需依赖关系的 ZIP 文件)。
- 提取该 ZIP 文件。
- 将
libs
目录中的所有 JAR 文件添加到您的类路径中。 - 将
google-api-services-analytics-v3-[version].jar
JAR 文件添加到您的类路径中。
第 3 步:设置示例代码
您需要创建一个名为 HelloAnalytics.java
的文件,其中将包含指定的示例代码。
- 将以下源代码复制或下载到
HelloAnalytics.java
中。 - 将先前下载的
client_secrets.JSON
移到示例代码所在的目录中。 - 将
KEY_FILE_LOCATION
的值替换为 Developers Console 中的相应值。
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; 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.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.io.IOException; /** * A simple example of how to access the Google Analytics API using a service * account. */ public class HelloAnalytics { private static final String APPLICATION_NAME = "Hello Analytics"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final String KEY_FILE_LOCATION = "<REPLACE_WITH_JSON_FILE>"; public static void main(String[] args) { try { Analytics analytics = initializeAnalytics(); String profile = getFirstProfileId(analytics); System.out.println("First Profile Id: "+ profile); printResults(getResults(analytics, profile)); } catch (Exception e) { e.printStackTrace(); } } /** * Initializes an Analytics service object. * * @return An authorized Analytics service object. * @throws IOException * @throws GeneralSecurityException */ private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream(KEY_FILE_LOCATION)) .createScoped(AnalyticsScopes.all()); // 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 Webproperties 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"); } } }
第 4 步:运行示例代码
在您启用了 Google Analytics(分析)API、安装了适用于 Java 的 Google API 客户端库并设置了示例源代码后,该示例代码就可以运行了。
如果您使用的是 IDE,请确保您已将默认运行目标设为 HelloAnalytics
类。或者,您也可以通过命令行编译并运行相应应用:
- 使用以下命令行编译示例应用:
javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
- 使用以下命令行运行示例应用:
java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics
当您完成上述步骤后,示例代码就会输出已获授权用户的首个 Google Analytics(分析)数据视图(配置文件)的名称以及过去 7 天内的会话数。
现在,借助已授权的 Google Analytics(分析)服务对象,您可以运行 Management API 参考文档中的任何代码示例。例如,您可以尝试更改代码来使用 accountSummaries.list 方法。