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

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

问题描述

我在寻找的编程方式登录到分析和获取数据的最简单方法。谷歌文档编写,并给出了OAuth 2.0用户涉及用户手动登录到与他的谷歌帐户,然后被重定向到我的网站有授权的例子。但是,这不是我想要达到的目标 - 我要建一个自动工具,需要有用户/密码或其他授权密钥是硬codeD,然后登录无需任何用户参与(这是一个周期性的报告工具)。

我已经找到一些有关API密钥,但我找不到任何例子,如何做到这一点,或如何到与谷歌的Java库。

我会指着我到正确的方向非常感激。这也可能是其他人怎么办呢最简单的方法有价值的线索 - 我想记录应该是简单


解决方案

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


  

服务帐户


  
  

可用于自动/离线/定期访问谷歌Analytics(分析)数据为自己的帐户。例如,要建立自己的谷歌分析数据的实时仪表板,并与其他用户共享。


  
  

有您需要按照配置服务帐户与谷歌Analytics(分析)合作几步:


  
  

      
  1. 注册API控制台中的一个项目。

  2.   
  3. 在谷歌的API控制台的API访问窗格下,创建一个设置为服务帐户的应用程序类型的客户端ID。

  4.   
  5. 登录到谷歌Analytics(分析)并导航到管理部分。

  6.   
  7. 选择您想要应用程序能够访问该帐户。

  8.   
  9. 添加的电子邮件地址,从第2步在API控制台中创建客户端ID,如选择谷歌Analytics帐户的用户。

  10.   
  11. 按照说明服务帐户来访问谷歌Analytics(分析)数据。

  12.   

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

PUH,我猜的API是如此之大谷歌是有问题的记录是一个简单的方法=)

然后我在加serviceaccount-CMDLINE样品中看了看code 分析 - CMDLINE样品。这是一个Playframework2的Java应用程序实现了一个非常基本的版本,
打印到System.out上面的例子:

 私有静态最终HttpTransport HTTP_TRANSPORT =新NetHttpTransport();
私有静态最终JsonFactory JSON_FACTORY =新JacksonFactory();公共静态结果指数(){
   GoogleCredential凭证= NULL;
   尝试{
        证书=新GoogleCredential.Builder()。setTransport(HTTP_TRANSPORT)
              .setJsonFactory(JSON_FACTORY)
              .setServiceAccountId(2363XXXXXXX@developer.gserviceaccount.com)
              .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
              .setServiceAccountPrivateKeyFromP12File(新文件(/你/路径/要/ privatekey / privatekey.p12))
              。建立();
     }赶上(GeneralSecurityException E){
         e.printStackTrace();
     }赶上(IOException异常五){
         e.printStackTrace();
     }     //设置并返回谷歌Analytics(分析)API客户端。
     分析分析=新Analytics.Builder(HTTP_TRANSPORT,JSON_FACTORY,证书).setApplicationName(
          谷歌 - 分析 - 你好,分析-API的样本)建()。     字符串配置文件ID =;
     尝试{
         配置文件ID = getFirstProfileId(分析);
     }赶上(IOException异常五){
        e.printStackTrace();
     }     GaData gaData = NULL;
     尝试{
        gaData = executeDataQuery(分析,提供ProfileID);
     }赶上(IOException异常五){
        e.printStackTrace();
     }
     printGaData(gaData);     返回OK(index.render(你的新的应用程序已经准备就绪。));
}私人静态字符串getFirstProfileId(分析分析)抛出IOException
    字符串配置文件ID = NULL;    //查询账催收。
    帐户帐户= analytics.management()账户()名单()的execute()。;    如果(accounts.getItems()。的isEmpty()){
        通信System.err.println(未发现账户);
    }其他{
        。字符串firstAccountId = accounts.getItems()得到(0).getId();        //查询网络媒体资源的集合。
        网络媒体资源网络媒体资源=
                analytics.management()网络载体()列表(firstAccountId).execute()。        如果(webproperties.getItems()。的isEmpty()){
            通信System.err.println(无网络载体找到);
        }其他{
            。字符串firstWebpropertyId = webproperties.getItems()得到(0).getId();            //查询型材集合。
            配置文件配置文件=
                    analytics.management()型材()列表(firstAccountId,firstWebpropertyId).execute()。            如果(profiles.getItems()。的isEmpty()){
                通信System.err.println(找不到配置文件);
            }其他{
                。配置文件ID = profiles.getItems()得到(0).getId();
            }
        }
    }
    返回配置文件ID;
}/ **
 *返回访问前25的有机搜索关键词和流量来源。核心报告API
 *用于检索这些数据。
 *
 * @参数分析用于访问API的分析服务对象。
 * @参数配置文件ID从其中检索数据的配置文件ID。
 返回:从API响应。
 *引发IOException TF的API出错。
 * /
私有静态GaData executeDataQuery(分析分析,弦乐配置文件ID)抛出IOException
    返回analytics.data()GA()获得(GA。+提供ProfileID,//表ID GA:+个人资料ID。
            2012-01-01,//开始日期。
            2012-01-14,//结束日期。
            嘎:探访)//指标。
            .setDimensions(嘎:源,GA:关键字)
            .setSort( - GA:参观,GA:源)
            .setFilters(嘎:中==有机)
            .setMaxResults(25)
            。执行();
}/ **
 *打印从核心报告API输出。该配置文件名称与每个沿印
 *列名,行中的所有数据。
 *
 * @参数结果数据从核心报告API返回。
 * /
私有静态无效printGaData(GaData结果){
    的System.out.println(打印效果的轮廓:+ results.getProfileInfo()getProfileName());    如果(results.getRows()== NULL || results.getRows()。的isEmpty()){
        的System.out.println(没有找到结果。);
    }其他{        //打印列标题。
        对于(GaData.ColumnHeaders头:results.getColumnHeaders()){
            System.out.printf(%30秒,header.getName());
        }
        的System.out.println();        //打印的实际数据。
        对于(列表<串GT;行:results.getRows()){
            对于(String列:行){
                System.out.printf(%30秒,列);
            }
            的System.out.println();
        }        的System.out.println();
    }
}

希望这有助于!

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).

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.

解决方案

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

Service Accounts

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.

There are a few steps you need to follow to configure service accounts to work with Google Analytics:

  1. Register a project in the APIs Console.
  2. In the Google APIs Console, under the API Access pane, create a client ID with the Application Type set to Service Account.
  3. Sign-in to Google Analytics and navigate to the Admin section.
  4. Select the account for which you want the application to have access to.
  5. Add the email address, from the Client ID created in the APIs Console from step #2, as a user of the selected Google Analytics account.
  6. Follow the instructions for Service Accounts to access Google Analytics data.

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

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

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

Hope this helps!

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

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