2012-01-31 100 views
7

我正在尋找以編程方式登錄到Analytics並獲取數據的最簡單方式。 Google文檔編寫並提供了Oauth 2.0的示例,其中涉及用戶使用他的Google帳戶手動登錄,然後通過授權重定向到我的網站。但這不是我想要實現的 - 我正在構建一個自動工具,需要用戶/密碼或任何其他授權密鑰進行硬編碼,然後在沒有任何用戶參與的情況下登錄(這是一個定期報告工具) 。java中的Google Analytics授權

我已經找到了關於API KEY的一些東西,但我找不到任何示例如何做到這一點,或者如何使用Google Java庫。

我將非常感謝指引我進入正確的方向。而且這對於其他人來說可能是最有價值的線索,如何以最簡單的方式來做到這一點 - 我認爲日誌記錄應該很簡單。

回答

2

我最終用2.4版本的Core Reporting解決了它 - 有你的gmail用戶/密碼的自動化,就像它應該是這麼簡單 - 我想知道爲什麼沒有例子如何在新的3.0版本中做到這一點。

核心報告2.4:http://code.google.com/intl/pl-PL/apis/analytics/docs/gdata/v2/gdataJava.html

+0

你真的後幫助我。 3.0版本的文檔非常混亂和無用。它忽略了很多重要的步驟,比如如何編譯client_secrets.json並指向這樣的'what !!?'鏈接。 再次,謝謝。 – 2012-05-23 20:32:59

+0

該頁面被谷歌刪除我面臨這個問題從過去20天你能分享代碼什麼是你用來訪問谷歌分析數據 – 2014-09-12 06:28:25

11

我有同樣的問題,我花了約1小時找到這個v3的文檔中:

服務帳戶

可用於自動/離線/計劃訪問您自己帳戶的Google Analytics數據。例如,要構建您自己的Google Analytics數據的實時信息中心並與其他用戶共享。

有您需要按照配置服務帳戶與谷歌Analytics(分析)工作幾步:

  1. 註冊API控制檯中的項目。
  2. 在Google API控制檯的「API訪問」窗格下,創建一個客戶端ID,並將「應用程序類型」設置爲「服務帳戶」。
  3. 登錄到Google Analytics並導航到管理部分。
  4. 選擇您希望應用程序有權訪問的帳戶。
  5. 從第2步中的API控制檯創建的客戶端ID中添加電子郵件地址,作爲選定Google Analytics帳戶的用戶。
  6. 按照服務帳戶的說明訪問Google Analytics數據。

在這裏閱讀更多: https://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization

PUH,我猜的API是如此之大谷歌是有問題的記錄是一個簡單的方法=)

然後我在看了看代碼plus-serviceaccount-cmdline-sample and analytics-cmdline-sample。這是在Playframework2 Java應用程序實現的一個非常基本的版本, 打印到System.out上面的例子:

private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 
private static final JsonFactory JSON_FACTORY = new JacksonFactory(); 

public static Result index() { 
    GoogleCredential credential = null; 
    try { 
     credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) 
       .setJsonFactory(JSON_FACTORY) 
       .setServiceAccountId("[email protected]") 
       .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY)) 
       .setServiceAccountPrivateKeyFromP12File(new File("/your/path/to/privatekey/privatekey.p12"))       
       .build(); 
    } catch (GeneralSecurityException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    // Set up and return Google Analytics API client. 
    Analytics analytics = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
      "Google-Analytics-Hello-Analytics-API-Sample").build(); 

    String profileId = ""; 
    try { 
     profileId = getFirstProfileId(analytics); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    GaData gaData = null; 
    try { 
     gaData = executeDataQuery(analytics, profileId); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    printGaData(gaData); 

    return ok(index.render("Your new application is ready.")); 
} 

private static String getFirstProfileId(Analytics analytics) throws IOException { 
    String profileId = null; 

    // Query accounts collection. 
    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 webproperties collection. 
     Webproperties webproperties = 
       analytics.management().webproperties().list(firstAccountId).execute(); 

     if (webproperties.getItems().isEmpty()) { 
      System.err.println("No Webproperties found"); 
     } else { 
      String firstWebpropertyId = webproperties.getItems().get(0).getId(); 

      // Query profiles collection. 
      Profiles profiles = 
        analytics.management().profiles().list(firstAccountId, firstWebpropertyId).execute(); 

      if (profiles.getItems().isEmpty()) { 
       System.err.println("No profiles found"); 
      } else { 
       profileId = profiles.getItems().get(0).getId(); 
      } 
     } 
    } 
    return profileId; 
} 

/** 
* Returns the top 25 organic search keywords and traffic source by visits. The Core Reporting API 
* is used to retrieve this data. 
* 
* @param analytics the analytics service object used to access the API. 
* @param profileId the profile ID from which to retrieve data. 
* @return the response from the API. 
* @throws IOException tf an API error occured. 
*/ 
private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException { 
    return analytics.data().ga().get("ga:" + profileId, // Table Id. ga: + profile id. 
      "2012-01-01", // Start date. 
      "2012-01-14", // End date. 
      "ga:visits") // Metrics. 
      .setDimensions("ga:source,ga:keyword") 
      .setSort("-ga:visits,ga:source") 
      .setFilters("ga:medium==organic") 
      .setMaxResults(25) 
      .execute(); 
} 

/** 
* Prints the output from the Core Reporting API. The profile name is printed along with each 
* column name and all the data in the rows. 
* 
* @param results data returned from the Core Reporting API. 
*/ 
private static void printGaData(GaData results) { 
    System.out.println("printing results for profile: " + results.getProfileInfo().getProfileName()); 

    if (results.getRows() == null || results.getRows().isEmpty()) { 
     System.out.println("No results Found."); 
    } else { 

     // Print column headers. 
     for (GaData.ColumnHeaders header : results.getColumnHeaders()) { 
      System.out.printf("%30s", header.getName()); 
     } 
     System.out.println(); 

     // Print actual data. 
     for (List<String> row : results.getRows()) { 
      for (String column : row) { 
       System.out.printf("%30s", column); 
      } 
      System.out.println(); 
     } 

     System.out.println(); 
    } 
} 

希望這有助於!

+0

這實際上是否工作?特別是P12文件:您是創建它還是下載?另外,這個代碼要運行的每臺機器都需要一個新的API密鑰? – Jeff 2014-05-05 06:06:00

+0

創建服務帳戶時,請勿選擇首選(由Google)JSON,但選擇P12。我花了一些時間尋找如何從JSON文件創建一個'PrivateKey',但在合理的時間內找不到任何東西。 – 2015-12-17 15:35:55

0

我試圖按照提供的示例進行編譯。我不知道這是3.0還是2.4,如果是的話,有沒有辦法讓示例代碼可以正常工作 - 適當選擇jar或什麼。

該示例的一個問題是setServiceAccountScopes的參數不再是字符串,而是Collections.singleton(AnalyticsScopes.Analytics.READ_ONLY)。

使用該示例同樣重要的是服務帳戶的正確配置。