2012-01-31 101 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)。

使用该示例同样重要的是服务帐户的正确配置。