java中的Google Analytics授权

时间:2012-01-31 18:23:40

标签: java google-analytics authorization

我正在寻找以编程方式登录Google Analytics并获取数据的最简单方法。 Google文档编写并提供了Oauth 2.0的示例,其中涉及用户手动登录其Google帐户,然后通过授权重定向到我的网站。但这不是我想要达到的目标 - 我正在构建一个自动工具,需要对用户/通行证或任何其他授权密钥进行硬编码,然后在没有任何用户参与的情况下登录(这是一个定期报告工具) 。

我已经找到了一些关于API KEY的内容,但我找不到任何示例如何做到这一点,或者如何使用Google java库找到它。

我非常感谢指向正确的方向。对于其他人来说,如果以最简单的方式做到这一点,这可能是有价值的线索 - 我认为记录应该很简单。

4 个答案:

答案 0 :(得分:12)

我有同样的问题,我花了大约1小时在v3文档中找到了这个:

  

服务帐户

     

适用于您自己帐户的Google Analytics数据的自动/离线/预定访问。例如,要构建自己的Google Analytics数据的实时信息中心,并与其他用户共享。

     

要配置服务帐户以使用Google Analytics,您需要执行以下几个步骤:

     
      
  1. 在API控制台中注册项目。
  2.   
  3. 在Google API控制台的“API访问”窗格下,创建一个客户端ID,其中“应用程序类型”设置为“服务帐户”。
  4.   
  5. 登录Google Analytics并导航至“管理”部分。
  6.   
  7. 选择您希望应用程序有权访问的帐户。
  8.   
  9. 从步骤2中API控制台中创建的客户端ID添加电子邮件地址,作为所选Google Analytics帐户的用户。
  10.   
  11. 按照服务帐户的说明访问Google Analytics数据。
  12.   

在这里阅读更多内容: https://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization

Puh,我猜这个API太大了,谷歌很容易记录它=)

然后我查看了 plus-serviceaccount-cmdline-sample 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("2363XXXXXXX@developer.gserviceaccount.com")
              .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();
    }
}

希望这有帮助!

答案 1 :(得分:2)

我最终使用2.4版本的Core Reporting解决了这个问题 - 使用你的gmail用户/ pass进行自动化,就像它应该的那样简单 - 我想知道为什么在新的3.0版本中没有例子如何做到这一点。

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

答案 2 :(得分:0)

我试图按照提供的示例进行操作,但不编译。我不知道这是3.0还是2.4,如果是的话,是否可以使示例代码正常工作 - 正确选择罐子或什么。

该示例的一个问题是setServiceAccountScopes的参数不再是字符串,而是Collections.singleton(AnalyticsScopes.Analytics.READ_ONLY)。

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

答案 3 :(得分:0)

作为对另一个问题的回答,我在Java中编写了一个适用于我的代码示例。

请参阅: https://stackoverflow.com/a/24043488/1391050