但是對於開發者來說,這樣的服務開不夠,開發者有可能會希望利用程式的方式進行Google Analytics 的追蹤查詢,所以Google又提供了Google Analytics API 的服務,讓開發者可以如使用Java等方式用程式來訪問Google Analytics。
最近在工作時,發現Google Analytics API 從2.0版升級到了3.0版本,所以很多以前用2.0版寫的程式都沒辨法跑了,必須要用到3.0版的方式才行。
在這裡我把如何申請Google Analytics及如何使用Google Analytics API做了一個紀錄,以供日後查讀:
一、申請及使用Google Analytics
首先你要先跟Google申請Google Analytics的使用,登入Google Analytics的首頁後,如果是第一次使用Google Analytics,要先設定想要追蹤分析的網頁網址。如果已經設定過了,就會進入報表頁面,如下所示:
按下"管理",可以看到如下畫面,分成"帳戶"、"資源"和"資料檢視"三個部份。
帳戶:為使用Google Analytics的管理者,可以設定不同的權限。
資源:為要追蹤分析的網站、行動應用程式或裝置 (如資訊站或銷售點裝置),在"資源"-->"追蹤資訊"-->"追錝程式碼裡"可以看到Google提供的JavaScript程式碼,需要放到想要追蹤分析的網頁程式碼中。
資料檢視:為存取報表的地方,在這裡可以設定多個資料檢視,例如只檢視某些的子網域名稱的流量等,在這裡也可以在"資料檢視"-->"檢視設定"內看到"資料檢視編號",也就是之後在Google Analytics API中會用到的"GA_id"。
二、申請及使用Google Analytics API
如果想要使用Google Analytics API的話,要先申請開通Google Analytics API的服務,登入Google Developers Console後,新建或選擇已經建好的專案,在左邊的功能例表中選擇"API和驗證"-->"API"啟用"Analytics API"的服務,
接著在"API和驗證"-->"憑證"中,先在"OAuth同意"畫面中填好資料儲存後,接著在"憑證"畫面中按下"新增憑證",並選擇"服務帳戶",如下所示:
接著選擇"P12",並按下建立,此時會瀏覽器會自動下載一個副檔名為"p12"的檔案,此檔包含了認證相關的資訊,並且會再"憑證"頁面下的"服務帳戶"看到一組"電子郵件地址"及"憑證指紋",p12檔案的名稱就是依照憑證指紋命名的。
接著就可以開始寫程式了,首先先到
https://developers.google.com/api-client-library/java/apis/#Google_Analytics_API
這裡下載Google Analytics API,解壓縮可以在裡面得到Google Analytics API的Client和Servier的Jar檔(放在不同層的資料夾內),記得在Java程式專案中將Jar檔引入Library中。
下面就是一個簡單Google Analytics API的程式範例:
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.Analytics.Data.Ga.Get;
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.util.List;
public class GoogleAnalyticsAPIExample {
//Application Name,可自取
private static final String APPLICATION_NAME = "Hello Analytics";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
//p12憑證檔的位置
private static final String KEY_FILE_LOCATION = "D:XXX.p12";
//上面有講到的在"憑證"頁面下的"服務帳戶"中的"電子郵件地址"
private static final String SERVICE_ACCOUNT_EMAIL = "XXX@developer.gserviceaccount.com";
//上面有講到的GA_id,記得前面要加上"ga:"
private static final String GA_id = "ga:XXX";
public static void main(String[] args) throws ClassNotFoundException {
try {
Analytics analytics = initializeAnalytics();
String profile = getFirstProfileId(analytics);
System.out.println("First Profile Id: " + profile);
printResults(getResults(analytics, profile));
//get()的最後一個參數是metrics
Get get= analytics.data().ga().get(GA_id , "2015-08-01", "2015-08-25", "ga:pageviews");
get.setDimensions("ga:browser,ga:pagePath");
GaData gaData = get.execute();
List<List<String>> rows = gaData.getRows();
for (List<String> row : rows){
for(String rowData : row){
System.out.print(rowData + " , ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Analytics initializeAnalytics() throws Exception {
// Initializes an authorized analytics service object.
// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
.setServiceAccountScopes(AnalyticsScopes.all())
.build();
// Construct the Analytics service object.
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
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");
}
}
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();
}
}
輸出如下所示(ID部份改成XXX) :
First Profile Id: XXXXX View (Profile) Name: 所有網站資料 Total Sessions: 10 / , 2 , /2014/06/gcm-serverphpjava.html , 1 , /2014/06/gcm-serverregistration-idphpjava.html , 1 , /2014/12/jquery.html , 1 , /2015/03/matlabarduino.html , 4 , /2015/04/android-android-studio.html , 1 , /2015/04/blog-post.html , 1 , /2015/04/intelasus-uefi-bios.html , 1 , /2015/06/ajaxjqueryservlet.html , 1 , /2015/07/spring-mvccontrollerview.html , 1 , /2015/08/springannotationtransactionjunitspringh.html , 1 , /search/label/Hibernate , 1 , /search/label/php , 1 ,
在這裡稍微說明一下,Dimensions和Metrics的差別,
Dimensions:用來分類數值資料的各種特性,如來訪的請求網址(ga:pagePath)、瀏覽器(ga:browser )、國家(ga:country )等。
Metrics :各種的數值資料,如總瀏覽次數(ga:pageviews)、不重覆的瀏覽次數(同一個Session瀏覽同一個頁面多次只算一次)(ga:uniquePageviews)等。
在Query Explorer中,可以設定各種Dimensions、Metrics等各種參數來進行模擬查詢,可以用來跟程式比對查詢結果是否正確。
在Dimensions & Metrics Explorer中,可以查詢各種Dimensions和Metrics及Google Analytics API會用到的各種參數。
附上原始碼:
GoogleAnalyticsAPIExample.java
參考資料:



沒有留言 :
張貼留言