I used to be able to query the Google Analytics API with my account\'s login & password. Google is now using OAuth for authentication which is great... The only issue is
Terry Seidler answered this nicely for php. I want to add a java code example.
Start by doing the required steps in the google api console as Terry explained:
Basically, you go to the Google API Console and create an App. Enable Google Analytics in the services tab. In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later. On the API Access page, in the Service account section, copy the email address (@developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors
Download the google analytics java client from: https://developers.google.com/api-client-library/java/apis/analytics/v3
Or add the following maven dependencies:
com.google.apis
google-api-services-analytics
v3-rev94-1.18.0-rc
com.google.http-client
google-http-client-jackson
1.18.0-rc
public class HellowAnalyticsV3Api {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public void analyticsExample() {
// This is the .p12 file you got from the google api console by clicking generate new key
File analyticsKeyFile = new File();
// This is the service account email address that you can find in the api console
String apiEmail = ;
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(apiEmail)
.setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
.setServiceAccountPrivateKeyFromP12File(analyticsPrivateKeyFile).build();
Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName()
.build();
String startDate = "2014-01-03";
String endDate = "2014-03-03";
String mertrics = "ga:sessions,ga:timeOnPage";
// Use the analytics object build a query
Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);
get.setDimensions("ga:city");
get.setFilters("ga:country==Canada");
get.setSort("-ga:sessions");
// Run the query
GaData data = get.execute();
// Do something with the data
if (data.getRows() != null) {
for (List row : data.getRows()) {
System.out.println(row);
}
}
}