Hello Analytics Reporting API v4; Java การเริ่มต้นอย่างรวดเร็วสำหรับแอปพลิเคชันที่ติดตั้ง

บทแนะนำนี้จะแนะนำขั้นตอนที่จำเป็นในการเข้าถึง Analytics Reporting API เวอร์ชัน 4

1. เปิดใช้ API

หากต้องการเริ่มต้นใช้งาน Analytics Reporting API v4 ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API เปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ

หมายเหตุ: หากต้องการสร้างรหัสเว็บไคลเอ็นต์หรือไคลเอ็นต์แอปพลิเคชันที่ติดตั้ง คุณต้องตั้งค่าชื่อผลิตภัณฑ์ในหน้าจอความยินยอม หากยังไม่ได้ทํา ระบบจะแจ้งให้กําหนดค่าหน้าจอขอความยินยอม

สร้างข้อมูลเข้าสู่ระบบ

  • เปิดหน้าข้อมูลเข้าสู่ระบบ
  • คลิกสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth
  • เลือกอื่นๆ ในส่วนประเภทแอปพลิเคชัน
  • ตั้งชื่อรหัสไคลเอ็นต์quickstart แล้วคลิกquickstart

จากหน้าข้อมูลเข้าสู่ระบบ ให้คลิกรหัสไคลเอ็นต์ที่สร้างขึ้นใหม่ แล้วคลิกดาวน์โหลด JSON แล้วบันทึกเป็น client_secrets.json คุณจะต้องใช้รหัสนี้ภายหลังในบทแนะนำ

2. ติดตั้งไลบรารีของไคลเอ็นต์

ในการติดตั้งไคลเอ็นต์ Java ของ Google Analytics API คุณต้องดาวน์โหลดไฟล์ ZIP ที่มี JAR ทั้งหมดที่คุณต้องการดึงข้อมูลและคัดลอกลงในคลาสพาธของ Java

  1. ดาวน์โหลดไลบรารีไคลเอ็นต์ Java ของ Analytics Reporting API v4 ซึ่งจะรวมเป็นไฟล์ ZIP ที่มีทรัพยากร Dependency ทั้งหมดที่จำเป็น
  2. แตกไฟล์ ZIP
  3. เพิ่ม JAR ทั้งหมดภายในไดเรกทอรี libs ไปยัง Classpath
  4. เพิ่ม jar google-api-services-analyticsreporting-v4-[version].jar ลงใน Classpath

รายละเอียดสภาพแวดล้อม Java

Eclipse

สำหรับ Eclipse โปรดดูคำถาม StackOverflow นี้เพื่อดูวิธีการเพิ่ม JAR ในคลาสพาธของโปรเจ็กต์

NetBeans

สำหรับ NetBeans โปรดดูคำถาม StackOverflow นี้เพื่อดูวิธีการเพิ่ม JAR ในคลาสพาธของโปรเจ็กต์

แนวคิดของ IntelliJ

สำหรับ IntelliJ IDEA โปรดดูคำถาม StackOverflow นี้เพื่อดูวิธีการเพิ่ม JAR ในคลาสพาธของโปรเจ็กต์

บรรทัดคำสั่ง

หากพัฒนาจากบรรทัดคำสั่ง ให้เพิ่มรายการต่อไปนี้ลงในการเรียกใช้คำสั่ง javac และ java

-classpath /path/to/directory/with/unzipped/jars

3. ตั้งค่าตัวอย่าง

คุณจะต้องสร้างไฟล์เดียวที่ชื่อ HelloAnalyticsReporting.java ซึ่งจะมีโค้ดตัวอย่างที่ระบุ

  • คัดลอกหรือดาวน์โหลดซอร์สโค้ดต่อไปนี้ลงใน HelloAnalyticsReporting.java
  • ย้าย client_secrets.json ที่ดาวน์โหลดก่อนหน้านี้ไปยังไดเรกทอรีเดียวกันกับโค้ดตัวอย่าง
  • แทนที่ค่าของ VIEW_ID ด้วยรหัสของข้อมูลพร็อพเพอร์ตี้ที่ต้องการเข้าถึง
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 java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.analyticsreporting.v4.AnalyticsreportingScopes;
import com.google.analyticsreporting.v4.Analyticsreporting;
import com.google.analyticsreporting.v4.model.ColumnHeader;
import com.google.analyticsreporting.v4.model.DateRange;
import com.google.analyticsreporting.v4.model.DateRangeValues;
import com.google.analyticsreporting.v4.model.Dimension;
import com.google.analyticsreporting.v4.model.GetReportsRequest;
import com.google.analyticsreporting.v4.model.GetReportsResponse;
import com.google.analyticsreporting.v4.model.Metric;
import com.google.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.analyticsreporting.v4.model.Report;
import com.google.analyticsreporting.v4.model.ReportRequest;
import com.google.analyticsreporting.v4.model.ReportRow;


/**
 * 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";

  // Replace with your view ID.
  private static final String VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // 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 Reporting";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      Analyticsreporting service = initializeAnalyticsReporting();

      GetReportsResponse response = getReport(service);
      printResponse(response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  /**
   * Initializes an authorized Analytics Reporting service object.
   *
   * @return The analytics reporting service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static Analyticsreporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

    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 authorization scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
            AnalyticsreportingScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");
    // Construct the Analytics Reporting service object.
    return new Analyticsreporting.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }

  /**
   * Query the Analytics Reporting API V4.
   * Constructs a request for the sessions for the past seven days.
   * Returns the API response.
   *
   * @param service
   * @return GetReportResponse
   * @throws IOException
   */
  private static GetReportsResponse getReport(Analyticsreporting service) throws IOException {
    // Create the DateRange object.
    DateRange dateRange = new DateRange();
    dateRange.setStartDate("7DaysAgo");
    dateRange.setEndDate("today");

    // Create the Metrics object.
    Metric sessions = new Metric()
        .setExpression("ga:sessions")
        .setAlias("sessions");

    //Create the Dimensions object.
    Dimension browser = new Dimension()
        .setName("ga:browser");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
        .setViewId(VIEW_ID)
        .setDateRanges(Arrays.asList(dateRange))
        .setDimensions(Arrays.asList(browser))
        .setMetrics(Arrays.asList(sessions));

    ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
    requests.add(request);

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest()
        .setReportRequests(requests);

    // Call the batchGet method.
    GetReportsResponse response = service.reports().batchGet(getReport).execute();

    // Return the response.
    return response;
  }

  /**
   * Parses and prints the Analytics Reporting API V4 response.
   *
   * @param response the Analytics Reporting API V4 response.
   */
  private static void printResponse(GetReportsResponse response) {

    for (Report report: response.getReports()) {
      ColumnHeader header = report.getColumnHeader();
      List<String> dimensionHeaders = header.getDimensions();
      List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
      List<ReportRow> rows = report.getData().getRows();

      if (rows == null) {
         System.out.println("No data found for " + VIEW_ID);
         return;
      }

      for (ReportRow row: rows) {
        List<String> dimensions = row.getDimensions();
        List<DateRangeValues> metrics = row.getMetrics();
        for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
          System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
        }

        for (int j = 0; j < metrics.size(); j++) {
          System.out.print("Date Range (" + j + "): ");
          DateRangeValues values = metrics.get(j);
          for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
            System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
          }
        }
      }
    }
  }
}

4. เรียกใช้ตัวอย่าง

หากใช้ IDE โปรดตรวจสอบว่าได้ตั้งค่าเป้าหมายการเรียกใช้เริ่มต้นเป็นคลาส HelloAnalytics แล้ว

  • แอปพลิเคชันจะโหลดหน้าการให้สิทธิ์ในเบราว์เซอร์
  • หากคุณยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ของคุณ ระบบจะแจ้งให้คุณลงชื่อเข้าใช้ หากคุณเข้าสู่ระบบบัญชี Google หลายบัญชี ระบบจะขอให้คุณเลือกบัญชีที่จะใช้ในการให้สิทธิ์

เมื่อทําตามขั้นตอนเหล่านี้เสร็จแล้ว ตัวอย่างจะแสดงจํานวนเซสชันในช่วง 7 วันที่ผ่านมาสำหรับข้อมูลพร็อพเพอร์ตี้ที่ระบุ