java中的谷歌分析授权 [英] Google Analytics authorization in java

查看:20
本文介绍了java中的谷歌分析授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for the simplest way of programmatically logging in into Analytics and get data. Google documentation writes and gives examples for Oauth 2.0 which involves a user manually logging into with his google account, and then being redirected to my site with authorization. But this is not what I want to achieve - I'm building an automatic tool that needs to have user/pass or any other authorization key to be hard-coded and then log in without any user involvement (this is a periodic reporting tool).

我已经找到了一些关于 API KEY 的信息,但我找不到任何示例来说明如何做到这一点,或者如何使用 Google Java 库来做到这一点.

I already found something about API KEY, but I can't find any example how to do that, or how to to that with Google java libraries.

我将非常感谢您为我指明正确的方向.此外,这对于其他人如何以最简单的方式进行操作可能是有价值的线索 - 我认为日志记录应该很简单.

I would be very grateful for pointing me into right direction. Also this may be valuable clue for others how to do it the simplest way - and I think logging should be simple.

推荐答案

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

I had the same problem and I took me about 1h to find this in the v3 documentation:

服务帐号

对于为您自己的帐户自动/离线/计划访问 Google Analytics 数据很有用.例如,构建您自己的 Google Analytics(分析)数据的实时信息中心并与其他用户共享.

Useful for automated/offline/scheduled access to Google Analytics data for your own account. For example, to build a live dashboard of your own Google Analytics data and share it with other users.

要配置服务帐户以使用 Google Analytics(分析),您需要遵循几个步骤:

There are a few steps you need to follow to configure service accounts to work with Google 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

Read more here: https://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization

呃,我猜这个 API 太大了,Google 很难用简单的方法记录它 =)

Puh, I guess the API is so big Google is having trouble documenting it an easy way =)

然后我查看了plus-serviceaccount-cmdline-sampleanalytics-cmdline-sample 中的代码.这是在 Playframework2 java 应用程序中实现的一个非常基本的版本打印到 System.out 作为上面的例子:

Then I looked at the code in the plus-serviceaccount-cmdline-sample and analytics-cmdline-sample. This is a very basic version implemented in a Playframework2 java app that prints to System.out as the examples above:

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();
    }
}

希望这有帮助!

这篇关于java中的谷歌分析授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆