java - 进行自己的查询 Google Analytics (Java)

标签 java maven google-analytics google-analytics-api

我正在尝试在网站中实现 Google 分析库,以便进行自己的查询并获取某种数据来管理它们。

我已按照示例进行操作,一切正常。但是,我只能编写示例查询(上周的访客)。我已经阅读了很多相关信息和文档,但仍然遇到同样的问题。

我确信一定有一种方法可以实现这一点,但实际上我无法编写任何代码来进行自己的查询。

代码是(我使用maven):

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.File;
import java.io.IOException;

/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class test {

    private static final String APPLICATION_NAME = "example";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final String KEY_FILE_LOCATION = //route to p.12 file;
    private static final String SERVICE_ACCOUNT_EMAIL = //mail example;


    public static void main(String[] args) {
        try {

            Analytics analytics = initializeAnalytics();

            String profile = getFirstProfileId(analytics);
            System.out.println("First Profile Id: " + profile);
            printResults(getResults(analytics, profile));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Analytics initializeAnalytics() throws Exception {
        // Initializes an authorized analytics service object.

        // Construct a GoogleCredential object with the service account email
        // and p12 file downloaded from the developer console.
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
                .setServiceAccountScopes(AnalyticsScopes.all())
                .build();

        // Construct the Analytics service object.
        return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    }

    private static String getFirstProfileId(Analytics analytics) throws IOException {
        // Get the first view (profile) ID for the authorized user.
        String profileId = null;

        // Query for the list of all accounts associated with the service account.
        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 for the list of properties associated with the first account.
            Webproperties properties = analytics.management().webproperties()
                    .list(firstAccountId).execute();

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

                // Query for the list views (profiles) associated with the property.
                Profiles profiles = analytics.management().profiles()
                        .list(firstAccountId, firstWebpropertyId).execute();

                if (profiles.getItems().isEmpty()) {
                    System.err.println("No views (profiles) found");
                } else {
                    // Return the first (view) profile associated with the property.
                    profileId = profiles.getItems().get(0).getId();
                }
            }
        }
        return profileId;
    }

    private static GaData getResults(Analytics analytics, String profileId) throws IOException {
        // Query the Core Reporting API for the number of sessions
        // in the past seven days.
        return analytics.data().ga()
                .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
                .execute();
    }

    private static void printResults(GaData results) {
        // Parse the response from the Core Reporting API for
        // the profile name and number of sessions.
        if (results != null && !results.getRows().isEmpty()) {
            System.out.println("View (Profile) Name: "
                    + results.getProfileInfo().getProfileName());
            System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
        } else {
            System.out.println("No results found");
        }
    }

}

请注意,进行查询的代码是:

private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
            .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
            .execute();
}

问题是:如何使用此代码设置查询的维度?

此查询有效(没有维度):

 private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
        return analytics.data().ga()
                .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration")
                .execute();
    }

这个不起作用(有尺寸):

 private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
        return analytics.data().ga()
                .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration",**"ga:userType"**)
                .execute();
    }

如果有任何帮助,我将不胜感激。非常感谢!

最佳答案

嗯,看来我的问题终于解决了。我自己回答是为了帮助有类似问题的人,并希望它也对他们有用。

答案很简单,有关 Google Analytics(分析)的文档有点令人困惑,但如果有人想要添加维度、指标(或编辑 Google Analytics(分析)的示例查询),只需在以下链接中添加代码即可:

https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

只需在查询示例之后添加此代码(如果您想添加维度):

setDimensions("ga:userType")

所以,最终的代码将是:

  private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
        return analytics.data().ga()
                .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration").setDimensions("ga:userType")
                .execute();
    }

注意,在主代码中,需要添加打印函数,如下所示:

public static void main(String[] args) {
    try {
        Analytics analytics = initializeAnalytics();
        printMobileTraffic(getMobileTraffic(analytics, profile));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

关于java - 进行自己的查询 Google Analytics (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413803/

相关文章:

java - GWT 2.6.1 编译时出现数字转换错误

c# - Google Analytics 维度和指标验证

java - 字符串,重复,但在Java中不从头开始(菱形模式

java - 如何从微调监听器访问变量?

java - Firebase 实时数据库 : Is there a way to avoid calling onDataChange when a value is removed?

java - 这个maven认证错误表示什么?

maven - Gradle无法解决Spring依赖关系

java - 流 takeWhile 用于同一管道中的排序流

javascript - 如何知道 Google Analytics 何时保存数据

pdf - 通过 PDF 文件中的链接跟踪传入的推荐网站?