Hello Analytics API: 설치된 애플리케이션을 위한 Java 빠른 시작

이 튜토리얼에서는 Google 애널리틱스 계정에 액세스하고, 애널리틱스 API를 쿼리하고, API 응답을 처리하고, 결과를 출력하는 데 필요한 단계를 안내합니다. 이 가이드에서는 Core Reporting API v3.0, Management API v3.0, OAuth2.0을 사용합니다.

1단계: Analytics API 사용 설정

Google 애널리틱스 API를 사용하려면 먼저 설정 도구를 사용해야 합니다. 이 도구는 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 방법을 안내합니다.

클라이언트 ID 만들기

사용자 인증 정보 페이지에서 다음을 수행합니다.

  1. 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
  2. 애플리케이션 유형으로 기타를 선택합니다.
  3. 사용자 인증 정보의 이름을 지정합니다.
  4. 만들기를 클릭합니다.

방금 만든 사용자 인증 정보를 선택하고 JSON 다운로드를 클릭합니다. 다운로드한 파일을 client_secrets.json로 저장합니다. 이 파일은 가이드의 후반부에 필요합니다.

2단계: Google 클라이언트 라이브러리 설치

Google 애널리틱스 API 자바 클라이언트를 설치하려면 압축을 풀어 자바 클래스 경로에 복사해야 하는 모든 jar가 포함된 ZIP 파일을 다운로드해야 합니다.

  1. Google 애널리틱스 자바 클라이언트 라이브러리를 다운로드합니다. 이 라이브러리는 필요한 모든 종속 항목이 포함된 ZIP 파일로 번들로 제공됩니다.
  2. ZIP 파일 추출
  3. libs 디렉터리 내의 모든 JAR을 클래스 경로에 추가합니다.
  4. google-api-services-analytics-v3-[version].jar jar를 클래스 경로에 추가합니다.

3단계: 샘플 설정

제공된 샘플 코드를 포함하는 HelloAnalytics.java라는 단일 파일을 만들어야 합니다.

  1. 다음 소스 코드를 HelloAnalytics.java로 복사하거나 다운로드합니다.
  2. 이전에 다운로드한 client_secrets.json를 샘플 코드와 동일한 디렉터리로 이동합니다.
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");
    }
  }
}

4단계: 샘플 실행

Analytics API를 사용 설정한 후 Java용 Google API 클라이언트 라이브러리를 설치하고 샘플 소스 코드를 설정하면 샘플을 실행할 수 있습니다.

IDE를 사용하는 경우 기본 실행 타겟이 HelloAnalytics 클래스로 설정되어 있는지 확인합니다.

  1. 애플리케이션이 브라우저에 인증 페이지를 로드합니다.
  2. 아직 Google 계정에 로그인하지 않았다면 로그인하라는 메시지가 표시됩니다. 여러 Google 계정에 로그인한 경우 승인에 사용할 계정 하나를 선택하라는 메시지가 표시됩니다.

이 단계를 완료하면 샘플에서 승인된 사용자의 첫 번째 Google 애널리틱스 보기 (프로필) 이름과 지난 7일간의 세션수를 출력합니다.

이제 승인된 애널리틱스 서비스 객체를 사용하여 Management API 참조 문서에 있는 코드 샘플을 실행할 수 있습니다. 예를 들어 accountSummaries.list 메서드를 사용하도록 코드를 변경할 수 있습니다.