Google Analytics(分析)

Management API - Java

The Google Analytics Management API provides five separate read-only feeds that allow your application to access Google Analytics account and configuration data. Your application can use the Java client library to access these feeds. For example, if your application needs a list of views (profiles) for a user, it can request the View (Profile) Feed. Similarly, if your application needs all the goal configuration data, including goal names for a particular view (profile), it can request the Goal Feed.

  1. Overview
  2. Setting up Your Environment
  3. Client Initialization
  4. Authorizing Requests
  1. Account Feed
  2. Web Property Feed
  3. View (Profile) Feed
  4. Goal Feed
  5. Segment Feed
  1. Error Handling

Overview

This document covers how to use Java to access Google Analytics data with the Google Analytics Management API. It assumes you have basic knowledge of the Java programming language. You will get the most out of this document if you are familiar with the following:

In the Google Analytics management model, each user can have a number of accounts, web properties, views (profiles), goals, and segments. The API provides a separate feed for each of these data types. Once you've authorized access to the API, you follow these steps to get data from either of these feeds:

  1. Create a query to define the data you want to extract through the Google Analytics Management API.
  2. Request data by calling the getFeed method on an authorized AnalyticsService object.
  3. Use the helper classes from the client library to handle the data returned from the API request.

The Management API automatically references version 2 of the Google Data Protocol. For more information, see the Google Data Protocol Developer's Guide.

Back to Top

Setting up Your Environment

The Java client library simplifies retrieving Analytics data by handling authorization tokens and by returning Analytics data from the Management API in Java objects. You can get the Java client library for the Analytics Management API in one of two ways:

Once you have your IDE set up correctly with the Google Data client libraries, reference the following JAR files in your CLASSPATH:

gdata-analytics-meta-2.1.jar
gdata-analytics-2.1.jar
gdata-core-1.0.jar
google-collect-1.0-rc1.jar
jsr305.jar

Back to Top

Client Initialization

Initialization Source

public static void initializeAnalyticsService() {
  try {
    analyticsService = new AnalyticsService(CLIENT_NAME);
    analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASSWORD);
  } catch (AuthenticationException e) {
    System.err.println("Authentication failed : " +
    e.getMessage());
  }
}

All calls to the Google Analytics API happen through the AnalyticsService object. Initializing an AnalyticsService is as easy as calling the constructor with the client application's name sent along as a parameter.

// Service Object to work with the Google Analytics Management API.
AnalyticsService analyticsService = new AnalyticsService("XTREME Sample App!");

Now that the service object has been instantiated, it's time to authenticate.

Back to Top

Authorizing requests

Before users can view their account information on the Google Analytics web site, they must first login in with a Google Account. In the same way, when users first access your application, they will need to authorize your application to access their data. The authorization in the API works using tokens.

Every request your application sends to the Google Analytics API must include an authorization token. The token also identifies your application to Google.

About authorization protocols

We recommend using OAuth 2.0 to authorize requests.

The Google Analytics API also supports older authorization options, such as OAuth 1.0, AuthSub, or ClientLogin; however, in most cases we don't recommend using those other options. If your application already uses those options, we recommend migrating to OAuth 2.0 if possible.

If your application has certain unusual authorization requirements, such as logging in at the same time as requesting data access (hybrid) or domain-wide delegation of authority (2LO), then you cannot currently use OAuth 2.0 tokens. In such cases, you must instead use OAuth 1.0 tokens and an API key. To find your application's API key:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Google Analytics API.
  4. In the sidebar on the left, select Credentials.
  5. The API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth 2.0: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

    • Public API keys: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports. If the key type you need does not already exist, create an API key by selecting Create New Key and then selecting the appropriate key type. Then enter the additional data required for that key type.

Authorizing requests with OAuth 2.0

All requests to the Google Analytics API must be authorized by an authenticated user.

The details of the authorization process, or "flow," for OAuth 2.0 vary somewhat depending on what kind of application you're writing. The following general process applies to all application types:

  1. When you create your application, you register it using the Google Developers Console. Google then provides information you'll need later, such as a client ID and a client secret.
  2. Activate the Google Analytics API in the Google Developers Console. (If the API isn't listed in the Developers Console, then skip this step.)
  3. When your application needs access to user data, it asks Google for a particular scope of access.
  4. Google displays a consent screen to the user, asking them to authorize your application to request some of their data.
  5. If the user approves, then Google gives your application a short-lived access token.
  6. Your application requests user data, attaching the access token to the request.
  7. If Google determines that your request and the token are valid, it returns the requested data.

Some flows include additional steps, such as using refresh tokens to acquire new access tokens. For detailed information about flows for various types of applications, see Google's OAuth 2.0 documentation.

Here's the OAuth 2.0 scope information for the Google Analytics API:

Scope Meaning
https://www.googleapis.com/auth/analytics.readonly Read-only access to the Analytics API.

To request access using OAuth 2.0, your application needs the scope information, as well as information that Google supplies when you register your application (such as the client ID and the client secret).

Tip: The Google APIs client libraries can handle some of the authorization process for you. They are available for a variety of programming languages; check the page with libraries and samples for more details.

Authorization

Authorization Source

public static void initializeAnalyticsService() {
  try {
    analyticsService = new AnalyticsService(CLIENT_NAME);
    analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASSWORD);
  } catch (AuthenticationException e) {
    System.err.println("Authentication failed : " +
    e.getMessage());
  }
}

Before users can view reports on the Google Analytics report interface, they must first log in with valid a Google Account. In the same way, your Java application must provide user access to Analytics. To do this, it must use the setUserCredentials() method on the AnalyticsService object, which handles all interaction between the Google Data API Java Library and the Analytics Management API.

With the AnalyticsService object, your application can authorize with one of three different methods:

The document Authorization describes the authorization method you should use for the type of application you are building.

This example uses the simplest ClientLogin method.

Authorization to Analytics is handled with the setUserCredentials method, which logs in via ClientLogin.

// ClientLogin Authorization.
analyticsService.setUserCredentials("INSERT_USERNAME_HERE", "INSERT_PASSWORD_HERE");

Back to Top

Account Feed

Account Feed Source

/**
 * Retrieves the account feed from the Management API and prints the
 * first entry.
 */
public static void printFirstAccount() {
  // Get feed
  ManagementFeed accountsFeed = getFeed(BASE_URL + "accounts?max-results=1");
  // Get Account
  ManagementEntry account = accountsFeed.getEntries().get(0);
  // Print Account
  System.out.println("--- Account Entry ---");
  System.out.println("Account ID: " + account.getProperty("ga:accountId"));
  System.out.println("Account Name: " + account.getProperty("ga:accountName"));
}

Once your application handles authentication, it can retrieve the list of accounts that your users have access to. The account feed is a top-level entity in the Management API and contains information about all the Google Analytics accounts available to the authenticated user. In this example, the printFirstAccount() method constructs an account feed query using the max-results URL parameter to set the maximum records returned to 1.

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/accounts?max-results=1");

Next, the code calls the getFeed() method on the AnalyticsService object, passing in the queryUrl as the first parameter. The second parameter is the client library class, which contains the results returned from the feed. Upon a sucessful response, the getFeed() method returns all the account feed data as a ManagementFeed object. Under the hood, the actual data being requested from the API is returned as an AtomPub XML feed and the client library takes care of parsing the XML into an an object.

// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed accountsFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

The ManagementFeed object contains a collection of ManagementEntry objects. This code example retrieves the first entry in the account feed and prints the account name and account ID to the system output.

//Get first account in the feed
ManagementEntry account = accountsFeed.getEntries().get(0);
// Print Account
System.out.println("--- Account Entry ---");
System.out.println("Account ID: " +  account.getProperty("ga:accountId"));
System.out.println("Account Name: " +
account.getProperty("ga:accountName"));

In addition, each account object contains an AnalyticsLink object that provides information about the child feed of this account — that is, the feed of all web properties connected to the account represented by the ManagementEntry. The following code gets that link and pulls information about the child feed.

AnalyticsLink link = account.getChildLink("analytics#webproperty");

System.out.println("URL for child feed: " + link.getHref());
System.out.println("Target kind for child feed: " + link.getTargetKind());

For a list of all the elements that can be returned from the Account Feed, see the Account Feed Response in the Management API Feed Reference.

Back to Top

Web Property Feed

Web Property Source

/**
 * Retrieves the web property feed from the Management API and prints the
 * first entry.
 */
public static void printFirstWebProperty() {
  ManagementFeed webPropertiesFeed = getFeed(BASE_URL +
      "accounts/~all/webproperties?max-results=1");
  ManagementEntry webProperty = webPropertiesFeed.getEntries().get(0);
  System.out.println("--- Web Property Entry ---");
  System.out.println("Account ID: " + webProperty.getProperty("ga:accountId"));
  System.out.println("Web Property ID: " + webProperty.getProperty("ga:webPropertyId"));
}

The web property feed returns information about the all the web properties for the authenticated user. The web property feed is child of an account entry. Each web property entry is a parent of a view (profile) feed. This URL will return a feed of all web properties available to the logged-in user.

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties");

It's also possible to only return all web properties under a single account. To do this, use the account ID instead of the ~all identifier. For example:

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/accounts/1234/webproperties");

Note: This is the exact same URL you would get by calling getHref() on this account's child link as shown in the account example above. The purpose is only to illustrate different ways to obtain web property data. There's no need to construct this URL yourself.

The following code calls a ManagementEntry object representing a single web property and prints details about that web property to the screen.

ManagementFeed webPropertiesFeed = getFeed(BASE_URL +
    "accounts/~all/webproperties");

ManagementEntry webProperty = webPropertiesFeed.getEntries().get(0);
System.out.println("--- Web Property Entry ---");
System.out.println("Account ID: " + webProperty.getProperty("ga:accountId"));
System.out.println("Web Property ID: " +
    webProperty.getProperty("ga:webPropertyId"));

For a list of all the elements that can be returned from the Web Property Feed, see the Web Property Feed Response in the Management API Feed Reference.

Back to Top

View (Profile) Feed

View (Profile) Source

/**
 * Retrieves the view (profile) feed from the Management API and prints the
 * first entry.
 */
public static void printFirstProfile() {
  ManagementFeed profilesFeed = getFeed(BASE_URL +
      "accounts/~all/webproperties/~all/profiles?max-results=1");
  ManagementEntry profile = profilesFeed.getEntries().get(0);

  System.out.println("--- View (Profile) Entry ---");
  System.out.println("Account ID: " + profile.getProperty("ga:accountId"));
  System.out.println("Web Property ID: " + profile.getProperty("ga:webPropertyId"));
  System.out.println("View (Profile) ID: " + profile.getProperty("ga:profileId"));
  System.out.println("Currency: " + profile.getProperty("ga:currency"));
  System.out.println("Timezone: " + profile.getProperty("ga:timezone"));
  System.out.println("Table ID: " + profile.getProperty("dxp:tableId"));
}

The view (profile) feed returns all the Google Analytics views (profiles) for the authenticated user. This feed is important because it provides the tableId for each view (profile). The tableId value is used in Google Analytics Core Reporting API queries—specifically the ids query parameter—to identify which view (profile) to retrieve data from.

The view (profile) feed is a child of a web property entry and each view (profile) entry is a parent of a goal Feed. To learn more about views (profiles), see the Views (Profiles) section of the Accounts and Views (Profiles) document.

The following code constructs a ManagementFeed containing all view (profile) entries accessible from the requested account.

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties/~all/profiles");

// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed profilesFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

Like before, you can filter which views (profiles) will be displayed by specifying an account ID and a web property ID in place of the ~all identifier for your request. Also, you can get the URL for a feed of all views (profiles) under a specific web property by following the child link from that web property.

Retrieving data from a view (profile) entry is done as follows:

// Get the first view (profile) from the ManagementFeed.
ManagementEntry profile = profilesFeed.getEntries().get(0);

System.out.println("--- View (Profile) Entry ---");
System.out.println("Account ID: " +  profile.getProperty("ga:accountId"));
System.out.println("Web Property ID: " +  profile.getProperty("ga:webPropertyId"));
System.out.println("View (Profile) ID: " + profile.getProperty("ga:profileId"));
System.out.println("Currency: " + profile.getProperty("ga:currency"));
System.out.println("Timezone: " + profile.getProperty("ga:timezone"));
System.out.println("Table ID: " + profile.getProperty("dxp:tableId"));

For a list of all the elements that can be returned from the View (Profile) Feed, see the View (Profile) Feed Response in the Management API Feed Reference.

Back to Top

Goal Feed

Goal Source

/**
 * Retrieves the goal feed from the Management API and prints the
 * first entry.
 */
public static void printFirstGoal() {
   ManagementFeed goalFeed = getFeed(BASE_URL +
      "accounts/~all/webproperties/~all/profiles/~all/goals?max-results=1");

  ManagementEntry goalEntry = goalFeed.getEntries().get(0);
  printGoal(goalEntry);
}


/**
 * Given a ManagementEntry object containing a goal, extracts the goal object,
 * determines the *type* of that goal object (Destination or Engagement), and
 * prints out relevant data.
 *
 * @param goalEntry The ManagementEntry representing a single goal.
 */
public static void printGoal(ManagementEntry goalEntry) {

  Goal goal = goalEntry.getGoal();
  System.out.println("Printing Goal #" + goal.getNumber());
  System.out.println("Name: " + goal.getName());
  System.out.println("Active? " + goal.getActive());
  System.out.println("Value: " + goal.getValue());

  if (goal.getDestination() != null) {
    Destination destination = goal.getDestination();
    System.out.println("Goal Type:  Destination");
    System.out.println("Destination - Case Sensitive: " +  destination.getCaseSensitive());
    System.out.println("Destination - Expression: " +  destination.getExpression());
    System.out.println("Destination - Match Type: " +  destination.getMatchType());
    System.out.println("Destination - Step 1 Required: : " +  destination.getStep1Required());

    System.out.println("Goal Steps: ");

    for (Step step : goal.getDestination().getSteps()) {
      System.out.println("Step: " + step.getNumber());
      System.out.println("Name: " + step.getName());
      System.out.println("Path: " + step.getPath());

    }
  } else if (goal.getEngagement() != null) {
    Engagement engagement = goal.getEngagement();
    System.out.println("Goal Type:  Engagement");
    System.out.println("Engagement - Type: " +  engagement.getType());
    System.out.println("Engagement - Threshhold Value: " +  engagement.getThresholdValue());
    System.out.println("Engagement - Comparison: " +  engagement.getComparison());

  }
}

The goal feed provides a quick way to access all the configured goal information for a particular view (profile). This feed is important because it provides access to goal names, goal types and goal status (active or inactive). The goal feed is a child of a view (profile) feed entry. Goal entries have no children.

Retrieving a ManagementFeed for goals is the same as retrieving one for accounts, web properties, or views (profiles). Just construct the URL and make the request:

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties/~all/profiles/~all/goals");

// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed goalsFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

For this type of entity, printing out the data is slightly different than for other entities. This is because a Goal object contains either a Destination or an Engagement object, depending on what type of Goal it is. Each of these objects has different corresponding data. As such, the code required to run through every possibility and print out the relevant data differs than that for other management entities.

if (goalsFeed.getEntries().size() == 0) {
 return;
}

ManagementEntry goalEntry = goalsFeed.getEntries().get(0);
Goal goal = goalEntry.getGoal();
System.out.println("Printing Goal #" + goal.getNumber());
System.out.println("Name: " + goal.getName());
System.out.println("Active? " + goal.getActive());
System.out.println("Value: " + goal.getValue());

if (goal.getDestination() != null) {
  Destination destination = goal.getDestination();
  System.out.println("Goal Type:  Destination");
  System.out.println("Destination - Case Sensitive: " +  destination.getCaseSensitive());
  System.out.println("Destination - Expression: " +  destination.getExpression());
  System.out.println("Destination - Match Type: " +  destination.getMatchType());
  System.out.println("Destination - Step 1 Required: : " +  destination.getStep1Required());

  System.out.println("Goal Steps: ");

  for (Step step : goal.getDestination().getSteps()) {
    System.out.println("Step: " + step.getNumber());
    System.out.println("Name: " + step.getName());
    System.out.println("Path: " + step.getPath());
  }
} else if (goal.getEngagement() != null) {
    Engagement engagement = goal.getEngagement();
    System.out.println("Goal Type:  Engagement");
    System.out.println("Engagement - Type: " +  engagement.getType());
    System.out.println("Engagement - Threshhold Value: " +  engagement.getThresholdValue());
    System.out.println("Engagement - Comparison: " +  engagement.getComparison());
}

For a list of all the elements that can be returned from the Goal Feed, see the Goal Feed Response in the Management API Feed Reference.

Back to Top

Segment Feed

Segment Source

/**
 * Retrieves the goal feed from the Management API and prints the
 * first entry.
 */
public static void printFirstSegment() {
  ManagementFeed segmentFeed = getFeed(BASE_URL + "segments");

  ManagementEntry segmentEntry = segmentFeed.getEntries().get(0);
  Segment segment = segmentEntry.getSegment();
  System.out.println("--- Segment ---");
  System.out.println("Segment ID: " + segment.getId());
  System.out.println("Segment Name: " + segment.getName());
  System.out.println("Segment Definition: " + segment.getDefinition().getValue());
}

The segment feed provides a listing of all the default and user created segments. A developer can then retrieve the ID of these segments and use them in the segment parameter of the Core Reporting API Data Feed request. Unlike the other feeds of the management API, this feed has no parent or child relationships.

// Construct query from a string.
URL queryUrl = new URL(
    "https://www.googleapis.com/analytics/v2.4/management/segments");

    ManagementEntry segmentEntry = segmentFeed.getEntries().get(0);

Each entry in the Segment Management Feed contains a Segment object. Extract the Segment object to print the relevant data about that segment.

// Output the data to the screen.
System.out.println("-------- Segment Feed Results --------"); ManagementEntry segmentEntry = segmentFeed.getEntries().get(0); Segment segment = segmentEntry.getSegment(); System.out.println("--- Segment ---"); System.out.println("Segment ID: " + segment.getId()); System.out.println("Segment Name: " + segment.getName()); System.out.println("Segment Definition: " + segment.getDefinition().getValue());

For a list of all the elements that can be returned from the Segment Feed, see the Segment Feed Response in the Management API Feed Reference.

Back to Top

Error Handling

The Google Data Java Client Library throws exceptions in the following cases.

  • User Login
    If a user supplies an incorrect username or password, or a similar error occurs, the AuthenticationException is thrown. If your application uses ClientLogin to authorize, and a program requests a token too frequently, the user is presented with a Captcha challenge response. See more information on using ClientLogin through Google Data APIs.
  • Network Issues
    If there is a network problem with during a request to the Google Analytics API, the IOException error is thrown.
  • Other Issues
    The ServiceException error is thrown for a variety of other request errors. For example, if an illegal combination of dimensions and metrics is requested, you will see this error. You will also see this error if you have run out of quota. You can get the specific error code returned by using the getCode() on the Service Exception class. The getMessage() method returns a description of the particular error.

Back to Top

要求进行身份验证

您需要登录到 Google+ 中才能执行该操作。

正在登录...

Google 开发者必须得到您的许可才能执行该操作。