本教程详细介绍了访问 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
- 打开服务账号页面。如果看到提示,请选择项目。
- 点击 创建服务账号,并输入服务账号的名称和说明。您可以使用默认服务账号 ID,也可以选择其他唯一的账号 ID。完成后,点击创建。
- 后面的服务账号权限(可选)部分无需设置。点击继续。
- 在向用户授予访问此服务账号的权限屏幕上,向下滚动到创建密钥部分。点击 创建密钥。
- 在随即显示的侧面板中,选择密钥的格式:建议使用 JSON。
- 点击创建。您的新公钥/私钥对随后会生成并下载到您的计算机上;该密钥仅此一份。要了解如何安全地存储密钥,请参阅管理服务账号密钥。
- 点击私钥已保存到您的计算机对话框中的关闭,然后点击完成以返回服务账号表格。
将服务账号添加到 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 方法。