Xin chào Analytics API: Khởi động nhanh Java cho các ứng dụng đã cài đặt

Tài liệu hướng dẫn này trình bày các bước cần thiết để truy cập vào tài khoản Google Analytics, truy vấn API Analytics, xử lý các phản hồi của API và xuất kết quả. API Báo cáo chính phiên bản 3.0, API Quản lý phiên bản 3.0API OAuth2.0 được sử dụng trong hướng dẫn này.

Bước 1: Bật Analytics API

Để bắt đầu sử dụng API Google Analytics, trước tiên bạn cần sử dụng công cụ thiết lập. Công cụ này sẽ hướng dẫn bạn cách tạo dự án trong Google API Console, bật API và tạo thông tin đăng nhập.

Tạo mã ứng dụng khách

Trên trang Thông tin xác thực:

  1. Nhấp vào Tạo thông tin xác thực rồi chọn Mã ứng dụng khách OAuth.
  2. Chọn Other cho APPLICATION TYPE (Loại ứng dụng).
  3. Đặt tên cho thông tin xác thực.
  4. Nhấp vào Tạo.

Chọn thông tin đăng nhập bạn vừa tạo rồi nhấp vào Tải JSON xuống. Lưu tệp đã tải xuống dưới dạng client_secrets.json; sau này bạn sẽ cần đến tệp này trong hướng dẫn.

Bước 2: Cài đặt Thư viện ứng dụng của Google

Để cài đặt Ứng dụng Java API của Google Analytics, bạn phải tải xuống một tệp zip chứa tất cả các tệp jar bạn cần để trích xuất và sao chép vào classpath Java.

  1. Tải thư viện ứng dụng Java của Google Analytics xuống. Thư viện này đóng gói dưới dạng tệp ZIP với tất cả các phần phụ thuộc bắt buộc.
  2. Giải nén tệp ZIP
  3. Thêm tất cả tệp JAR trong thư mục libs vào classpath.
  4. Thêm tệp jar google-api-services-analytics-v3-[version].jar vào classpath.

Bước 3: Thiết lập mẫu

Bạn cần tạo một tệp có tên HelloAnalytics.java chứa mã mẫu đã cho.

  1. Sao chép hoặc tải mã nguồn sau xuống HelloAnalytics.java.
  2. Di chuyển client_secrets.json đã tải xuống trước đó vào cùng thư mục với mã mẫu.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
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;
import java.io.InputStreamReader;


/**
 * A simple example of how to access the Google Analytics API.
 */
public class HelloAnalytics {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloAnalytics.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // The directory where the user's credentials will be stored.
  private static final File DATA_STORE_DIR = new File(
      System.getProperty("user.home"), ".store/hello_analytics");

  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

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

  private static Analytics initializeAnalytics() throws Exception {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloAnalytics.class
            .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all auth scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
        AnalyticsScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");

    // 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 properties 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");
    }
  }
}

Bước 4: Chạy mẫu

Sau khi bạn bật API Analytics, hãy cài đặt thư viện ứng dụng API của Google cho Java và thiết lập mã nguồn mẫu để mẫu sẵn sàng chạy.

Nếu bạn đang dùng IDE, hãy đảm bảo bạn đã đặt đích chạy mặc định thành lớp HelloAnalytics.

  1. Ứng dụng sẽ tải trang cấp phép trong trình duyệt.
  2. Nếu chưa đăng nhập vào Tài khoản Google, bạn sẽ được nhắc đăng nhập. Nếu đăng nhập vào nhiều Tài khoản Google, bạn sẽ được yêu cầu chọn một tài khoản để sử dụng cho quy trình uỷ quyền.

Khi bạn hoàn tất những bước này, mẫu sẽ hiển thị tên của chế độ xem (hồ sơ) Google Analytics đầu tiên của người dùng được uỷ quyền và số phiên trong 7 ngày qua.

Với đối tượng dịch vụ Analytics được uỷ quyền, giờ đây, bạn có thể chạy mọi mã mẫu có trong tài liệu tham khảo về API Quản lý. Ví dụ: bạn có thể thử thay đổi mã để sử dụng phương thức accountSummaries.list.