本教學課程逐步介紹存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應,並輸出結果的必要步驟。本教學課程使用 Core Reporting API 3.0 版、Management API v3.0 和 OAuth2.0。
步驟 1:啟用 Analytics (分析) API
如要開始使用 Google Analytics API,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。
建立用戶端 ID
在「憑證」頁面中:
- 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」。
- 在「APPLICATION TYPE」中選取「其他」。
- 輸入憑證名稱。
- 點選「建立」。
選取您剛剛建立的憑證,然後按一下「Download JSON」(下載 JSON)。將下載的檔案儲存為 client_secrets.json
,稍後用於教學課程。
步驟 2:安裝 Google 用戶端程式庫
如要安裝 Google Analytics API Java 用戶端,您必須下載包含所有 jar 的 ZIP 檔案,然後複製到 Java 類別路徑中。
- 下載 Google Analytics (分析) Java 用戶端程式庫,這個程式庫會封裝為 ZIP 檔案,內含所有必要依附元件。
- 將 ZIP 檔案解壓縮
- 將
libs
目錄中的所有 JAR 新增至類別路徑。 - 將
google-api-services-analytics-v3-[version].jar
jar 新增到您的類別路徑中。
步驟 3:設定範例
您必須建立名為 HelloAnalytics.java
的單一檔案,其中含有指定的程式碼範例。
- 將下列原始碼複製或
下載至
HelloAnalytics.java
。 - 將先前下載的
client_secrets.json
移至與程式碼範例相同的目錄中。
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 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.File; import java.io.IOException; import java.io.InputStreamReader; /** * 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"; // 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"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static NetHttpTransport httpTransport; private static FileDataStoreFactory dataStoreFactory; public static void main(String[] args) { try { Analytics analytics = initializeAnalytics(); String profile = getFirstProfileId(analytics); printResults(getResults(analytics, profile)); } catch (Exception e) { e.printStackTrace(); } } private static Analytics initializeAnalytics() throws Exception { 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 auth scopes. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow .Builder(httpTransport, JSON_FACTORY, clientSecrets, AnalyticsScopes.all()).setDataStoreFactory(dataStoreFactory) .build(); // Authorize. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); // 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 properties 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:執行範例
啟用 Analytics API 後, 已安裝 Java 適用的 Google API 用戶端程式庫, 然後設定可開始執行的範例原始碼。
如果您使用的是 IDE,請務必將預設的執行目標設為 HelloAnalytics
類別。
- 應用程式會在瀏覽器中載入授權頁面。
- 如果您尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個 Google 帳戶,系統會要求您選取其中一個帳戶進行授權。
完成這些步驟後,範例會輸出授權使用者的第一個 Google Analytics (分析) 資料檢視 (設定檔) 名稱,以及最近七天的工作階段數。
現在,您可以使用已授權的 Analytics (分析) 服務物件,執行 Management API 參考文件中的任何程式碼範例。例如,您可以嘗試變更程式碼,改用 accountSummaries.list 方法。