Я пытаюсь реализовать библиотеку аналитики google на веб-сайте, чтобы самостоятельно создавать свои запросы и получать данные о них для управления ими.Выполнение собственных запросов google analytics (JAVA)
Я следовал примеру, и все работает нормально. Однако я могу только запросить пример запроса (посетителей на прошлой неделе). Я прочитал много информации и документации об этом, и у меня все еще такая же проблема.
Я уверен, что должен быть способ сделать это, но на самом деле я не могу ничего кодировать, чтобы делать свои собственные запросы.
Код (я использую Maven):
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 test {
private static final String APPLICATION_NAME = "example";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = //route to p.12 file;
private static final String SERVICE_ACCOUNT_EMAIL = //mail example;
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");
}
}
}
Обратите внимание, что код, который делает запросы на:
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 GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration")
.execute();
}
Это одна не работает (с размерами):
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration",**"ga:userType"**)
.execute();
}
Я был бы признателен за любую помощь. Большое спасибо!
Второй пример кода не делает запрос, он возвращает идентификатор для первого представления данных в первой учетной записи, разрешенной вашими учетными данными .. Фактический запрос находится в методе getResults, в частности, analytics.data(). ga(). get ("ga:" + profileId, "7daysAgo", "today", "ga : сессии ") Execute();. (возврат из данных идентификатора вида, начинающийся семь дней назад, до сегодняшнего дня с количеством сеансов в качестве показателя). Это строка, которую нужно изменить. –
Вы правы @EikePierstorff. Я отредактировал свой ответ. К сожалению, проблема все еще существует –
В документах есть полный пример, не помогает ли это (https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide)? Ссылка на параметры и показатели показывает, какие значения вы можете запросить (https://developers.google.com/analytics/devguides/reporting/core/dimsmets).Метрики (числа) добавляются к запросу в качестве четвертого параметра метода get (ga: сеансы в вашем примере, используйте список с разделителями-запятыми для нескольких показателей), и вы можете связать с ним методы setDimensions для категориальных данных (т.е. setDimensions ("ga: source, ga: keyword"). –