gpt4 book ai didi

java - Google Analytics Reports v4 API 不在浏览器中显示图表

转载 作者:行者123 更新时间:2023-11-30 05:19:53 25 4
gpt4 key购买 nike

我已开始使用 Google Analytics Reports v4 API 进行更新。我没有先验知识。我正在尝试生成一个简单的图表。

我已经使用了谷歌分析文档中给出的示例代码。但我根本没有收到报告,而是一条消息

Received verification code. You may now close this window...

不知道为什么会显示这样的消息。看起来没有可用的数据。到目前为止,我已经完成了以下操作来运行该项目。

  1. Create the project.
  2. Crate the service.
  3. Create the View with email address retrieved from service's JSON file.
  4. Create client_secrets.json and add it to my src\ folder.
  5. Get the view id and use it in my code.

我不知道从这里该往哪个方向走。有很多事情需要注意,而且文档也非常健康。对于像我这样的初学者来说,决定选择正确的部件是很困难的。

此外,我还有以下问题需要解答。

  1. Is it possible to run it on local server such as Tomcat?
  2. Is google analytics free? Can I use it using my gmail email address?
  3. Is it important to have domain and hosting to get the report in browser?
  4. Am I need to give valid return URL while setting the client settings?
  5. Why am I need to give View ID? If it is to give manually then how do I generate the report dynamically?

这是我的环境和Java代码。请查看并帮助我找到解决方案。我期待一个流畅、干净的指南。

环境

  1. 带有 Tomcat 9.0.30 服务器的 Eclipse Java EE。
  2. 使用 Java 作为编程语言。

代码

package com.garinst;

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.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting;
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader;
import com.google.api.services.analyticsreporting.v4.model.DateRange;
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues;
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest;
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse;
import com.google.api.services.analyticsreporting.v4.model.Metric;
import com.google.api.services.analyticsreporting.v4.model.Dimension;
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.api.services.analyticsreporting.v4.model.Report;
import com.google.api.services.analyticsreporting.v4.model.ReportRequest;
import com.google.api.services.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 = "96519128";

// 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 File DATA_STORE_DIR = new File("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));
}
}
}
}
}
}

Maven 依赖项

<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.30.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client-gson -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
<version>1.30.7</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analyticsreporting</artifactId>
<version>v4-rev20190904-1.30.1</version>
</dependency>
</dependencies>

最佳答案

Received verification code. You may now close this window...

这是 Oauth2 流程的第一步,一旦用户授权您访问其 Google 分析数据,此代码就会返回到您的应用程序,然后交换为访问 token 。您可能想查看 Oauth2,或者您可以按照它的说明操作并关闭窗口。

Is google analytics free? Can I use it using my gmail email address?

是的,Google 分析 API 可以免费使用。用户使用他们在 Google Analytics 帐户中设置的用户登录您的应用程序

Is it important to have domain and hosting to get the report in browser?

您需要将应用程序托管在用户可以访问的某个位置。请记住,Google Analytics 以 Json 形式返回数据,您可以自行构建报告并将其显示给用户。

Am I need to give valid return URL while setting the client settings?

如果您要将其托管在网络上,则需要一个有效的重定向 URI 才能完成授权过程。

Why am I need to give View ID? If it is to give manually then how do I generate thereport dynamically?

用户可以拥有多个 Google Analytics 帐户,每个帐户可以正确拥有多个网站,并且每个网络资源可以拥有多个 View 。您的用户需要能够决定他们想要查看哪个 View 的数据。

注意

该系统用于从谷歌分析请求数据,原始数据返回为 json 。它不会作为您自己创建图形所需的报告返回。 Oauth2 登录适用于多用户系统,任何人都可以登录您的应用程序,它不会只显示您的个人数据。

评论问题

Is there any possibility to get the dynamic result such as user will login and get his own data?

这就是 oauth2 的工作原理。登录您的应用程序的用户可以访问他们的数据

How is it possible to display the JSON data in graphical reports as available in google analytics?

您需要创建一个图形库,或者找到第三方已为您创建的图形库,然后插入从 Google 分析返回的数据。 API 仅返回 json 数据,它们无法控制开发人员如何显示它。

关于java - Google Analytics Reports v4 API 不在浏览器中显示图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59728880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com