Java 如何获取访问令牌以获取google analytics数据?

Java 如何获取访问令牌以获取google analytics数据?,java,google-analytics,Java,Google Analytics,我正在使用谷歌分析为我的网站获取数据。我已经在QueryExplorer上测试了这些查询。但是我无法在OAuth的代码中实现它。我需要一个访问令牌来运行我的查询,但我的问题是我无法获取访问令牌。有谁能指导我完成这件事吗。 有人能解释一下谷歌开发者控制台和分析账户之间的关系吗。 请参阅一些实施文档。假设这是您自己想要访问的数据,并且您可以访问Google Analytics帐户网站。我建议您使用服务帐户 Google开发者控制台是您向Google注册应用程序的地方,它与您的Google Analy

我正在使用谷歌分析为我的网站获取数据。我已经在QueryExplorer上测试了这些查询。但是我无法在OAuth的代码中实现它。我需要一个访问令牌来运行我的查询,但我的问题是我无法获取访问令牌。有谁能指导我完成这件事吗。 有人能解释一下谷歌开发者控制台和分析账户之间的关系吗。
请参阅一些实施文档。

假设这是您自己想要访问的数据,并且您可以访问Google Analytics帐户网站。我建议您使用服务帐户

Google开发者控制台是您向Google注册应用程序的地方,它与您的Google Analytics帐户没有任何关系

我再次建议您使用服务帐户,并在Google开发者控制台上创建服务帐户凭据。获取服务帐户电子邮件地址将其作为用户添加到帐户级别的google analytics admin部分为其提供读取权限它必须在帐户级别。这将允许服务帐户读取您的谷歌分析数据

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.File;
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 = "/path/to/your.p12";
  private static final String SERVICE_ACCOUNT_EMAIL = "<SERVICE_ACCOUNT_EMAIL>@developer.gserviceaccount.com";
  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();
    }
  }

  private static Analytics initializeAnalytics() throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
        .setServiceAccountScopes(AnalyticsScopes.all())
        .build();

    // 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");
    }
  }
}
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
导入com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.gson.GsonFactory;
导入com.google.api.services.analytics.analytics;
导入com.google.api.services.analytics.AnalyticsScopes;
导入com.google.api.services.analytics.model.Accounts;
导入com.google.api.services.analytics.model.GaData;
导入com.google.api.services.analytics.model.Profiles;
导入com.google.api.services.analytics.model.Webproperties;
导入java.io.File;
导入java.io.IOException;
/**
*如何使用服务访问Google Analytics API的简单示例
*帐户。
*/
公共类HelloAnalytics{
私有静态最终字符串应用程序\u NAME=“Hello Analytics”;
私有静态最终JsonFactory JSON_FACTORY=GsonFactory.getDefaultInstance();
私有静态最终字符串密钥文件位置=“/path/to/your.p12”;
私有静态最终字符串服务\u ACCOUNT\u EMAIL=“@developer.gserviceaccount.com”;
公共静态void main(字符串[]args){
试一试{
分析=初始化分析();
字符串配置文件=getFirstProfileId(分析);
System.out.println(“第一个配置文件Id:+Profile”);
打印结果(getResults(分析、配置文件));
}捕获(例外e){
e、 printStackTrace();
}
}
私有静态分析initializeAnalytics()引发异常{
//初始化授权的分析服务对象。
//使用服务帐户电子邮件构造GoogleCredential对象
//以及从开发者控制台下载的p12文件。
HttpTransport HttpTransport=GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential=新建GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_工厂)
.setServiceAccountId(服务\帐户\电子邮件)
.SetServiceAccountPrivateKeyFromp12文件(新文件(密钥文件位置))
.setServiceAccountScopes(AnalyticsScopes.all())
.build();
//构造分析服务对象。
返回新的Analytics.Builder(httpTransport、JSON_工厂、凭证)
.setApplicationName(应用程序名称).build();
}
私有静态字符串getFirstProfileId(分析)引发IOException{
//获取授权用户的第一个视图(配置文件)ID。
字符串profileId=null;
//查询与服务帐户关联的所有帐户的列表。
Accounts Accounts=analytics.management().Accounts().list().execute();
if(accounts.getItems().isEmpty()){
System.err.println(“未找到帐户”);
}否则{
字符串firstAccountId=accounts.getItems().get(0.getId();
//查询与第一个帐户关联的属性列表。
Webproperties属性=analytics.management().Webproperties()
.list(firstAccountId).execute();
if(properties.getItems().isEmpty()){
System.err.println(“未找到Webproperties”);
}否则{
字符串firstWebpropertyId=properties.getItems().get(0.getId();
//查询与属性关联的列表视图(配置文件)。
Profiles Profiles=analytics.management().Profiles()
.list(firstAccountId,firstWebpropertyId).execute();
if(profiles.getItems().isEmpty()){
System.err.println(“未找到视图(配置文件”);
}否则{
//返回与属性关联的第一个(视图)配置文件。
profileId=profiles.getItems().get(0.getId();
}
}
}
返回profileId;
}
私有静态GaData getResults(Analytics Analytics,String profileId)引发IOException{
//查询Core Reporting API以获取会话数
//在过去的七天里。
return analytics.data().ga()
.get(“ga:+profileId”、“7daysAgo”、“今天”、“ga:sessions”)
.execute();
}
私有静态void打印结果(GaData结果){
//解析来自的核心报告API的响应
//配置文件名称和会话数。
if(results!=null&&!results.getRows().isEmpty()){
System.out.println(“视图(配置文件)名称:”
+results.getProfileInfo().getProfileName());
System.out.println(“总会话:+results.getRows().get(0.get(0));
}否则{
System.out.println(“未找到结果”);
}
}
}

直接从

中撕下的代码谢谢您的帮助,我正在尝试这个。我已经添加了所有JAR,但它给了我一个错误:java.lang.NoClassDefFoundError:com/google/api/client/http/HttpMethod