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. 서비스 계정 페이지를 엽니다. 메시지가 표시되면 프로젝트를 선택합니다.
  2. 서비스 계정 만들기를 클릭한 다음 서비스 계정의 이름과 설명을 입력합니다. 기본 서비스 계정 ID를 사용하거나 다른 고유한 ID를 선택할 수도 있습니다. 완료하면 만들기를 클릭합니다.
  3. 이어지는 서비스 계정 권한(선택사항) 섹션은 선택하지 않아도 됩니다. 계속을 클릭합니다.
  4. 사용자에게 이 서비스 계정에 대한 액세스 권한 부여 화면에서 키 만들기 섹션이 나올 때까지 아래로 스크롤합니다. 키 만들기를 클릭합니다.
  5. 표시되는 측면 패널에서 키에 사용할 형식을 선택합니다. JSON을 사용하는 것이 좋습니다.
  6. 만들기를 클릭합니다. 새로운 공개 키/비공개 키 쌍이 생성되어 기기에 다운로드됩니다. 생성된 파일은 이 키의 유일한 사본으로 사용됩니다. 키를 안전하게 보관하는 방법을 자세히 알아보려면 서비스 계정 키 관리를 참조하세요.
  7. 비공개 키가 컴퓨터에 저장됨 대화상자에서 닫기를 클릭한 다음 완료를 클릭하여 서비스 계정 표로 돌아갑니다.

Google 애널리틱스 계정에 서비스 계정 추가

새로 만든 서비스 계정에는 <projectId>-<uniqueId>@developer.gserviceaccount.com이라는 이메일 주소가 포함됩니다. 이 이메일 주소를 사용하여 API를 통해 액세스할 Google 애널리틱스 계정에 사용자를 추가합니다. 이 튜토리얼에서는 읽기 및 분석 권한만 있으면 됩니다.

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를 샘플 코드와 동일한 디렉터리로 이동합니다.
  3. KEY_FILE_LOCATION의 값을 Play Console의 적절한 값으로 대체합니다.
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.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.io.IOException;


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


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "<REPLACE_WITH_JSON_FILE>";
  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();
    }
  }

  /**
   * Initializes an Analytics service object.
   *
   * @return An authorized Analytics service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(AnalyticsScopes.all());

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

4단계: 샘플 실행

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

IDE를 사용하는 경우 기본 실행 타겟이 HelloAnalytics 클래스로 설정되어 있는지 확인합니다. 그렇지 않으면 명령줄에서 애플리케이션을 컴파일하고 실행할 수 있습니다.

  1. 다음을 사용하여 샘플을 컴파일합니다.
    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
  2. 다음을 사용하여 샘플을 실행합니다.
    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics

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

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