2016-03-15 3 views
1

У меня возникают проблемы с тем, чтобы программа Hello Analytics работала с API Google Analytics v3. Я перешел на сайт разработчиков Google и выполнил шаги по настройке пользователя и получению учетных данных и добавлению пользователя в аналитику. Я загрузил этот код с веб-страницы https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-javaПрограмма Google Analytics для Google API getID()

Я добавил файлы jar в путь к классам, и ни один из них не дал мне ошибок в Java-коде. Однако на строках 71,80 и 90 появляется ошибка, указывающая: «Метод getId() не определен для типа Object«

Я понимаю, что этот метод не определен в объекте типа. Я просмотрел иерархию вызовов и заметил, что он не существует на уровнях Object, List или Account в файлах .jar, предоставленных Google.

Я запускаю java версию 1.8.0_73 с панели управления java. Можете ли вы сказать мне, что не так, или как решить эту проблему?

Вот код от Google:

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

Возможно, это потому, что в вашем ответе нет аккаунта? [Исходный код] (https://developers.google.com/resources/api-libraries/documentation/analytics/v3/java/latest/com/google/api/services/analytics/model/Account.html#getId ()) четко определил 'getId()'. Помните, что вам нужно добавить свой адрес электронной почты учетной записи службы в запрос Analytics (профиль), который вы хотите запросить. – Matt

+0

Я добавил адрес электронной почты и путь к файлу .p12. Однако я получаю ошибку, прежде чем я даже запустил код. Он отображается как ошибки. Поэтому я даже не получаю ошибку времени выполнения. – user3622312

+1

Я понял проблему с кодом. В примере импортированы учетные записи, веб-свойства и профили. Однако это списки объектов Account, Webproperty и Profile. Мне пришлось импортировать эти объекты в код, а затем набирать соответствующую строку, чтобы она работала. Вот пример. Строка firstWebpropertyId = ((Webproperty) properties.getItems(). Get (0)). GetId(); – user3622312

ответ

0

Значение вы обеспечиваете для переменной SERVICE_ACCOUNT_EMAIL т.е. "@ developer.gserviceaccount.com" вам нужно добавить его в Google Analytics 'User Management'. Вы найдете его в Admin> User Management. Добавьте здесь SERVICE_ACCOUNT_EMAIL, и он начнет работать.