Java calls Google Analytics API for website statistics

Source: Internet
Author: User


The following code is a piece of code that I modified and commented out according to the official Google Documents to collect statistics on access traffic and other information.
[Java]
Package cn.edu. KFC. bean;
Import com. google. gdata. client. analytics. AnalyticsService;
Import com. google. gdata. client. analytics. DataQuery;
Import com. google. gdata. data. analytics. AccountEntry;
Import com. google. gdata. data. analytics. AccountFeed;
Import com. google. gdata. data. analytics. DataEntry;
Import com. google. gdata. data. analytics. DataFeed;
Import com. google. gdata. util. AuthenticationException;
Import com. google. gdata. util. ServiceException;
Import java. io. IOException;
Import java.net. MalformedURLException;
Import java.net. URL;
Public class GoogleAnalytics {
// Use the ClientLogin method to access Google Analytics. The two constants store the user name and password respectively.
Private static final String CLIENT_USERNAME = "anyone@gmail.com"; // Google account
Private static final String CLIENT_PASS = "1234567"; // Google Password
Private static final String TABLE_ID = "ga: 715123"; // The table id of the Google Analytics configuration file that this account has the right to access
 
Public void myTest (){
Try {
/*
* The system creates a service object. A service object parameter is a string that represents the application name. Then, the system will use the setUserCredentials method for processing.
* Google Analytics (analysis) authorization.
*/
// Service Object to work with the Google Analytics Data Export API.
AnalyticsService analyticsService = new AnalyticsService ("gaExportAPI_acctSample_v2.0 ");
// Client Login Authorization.
AnalyticsService. setUserCredentials (CLIENT_USERNAME, CLIENT_PASS );
 
// Get data from the Account Feed.
GetAccountFeed (analyticsService); // get account information
 
// Access the Data Feed if the Table Id has been set.
If (! TABLE_ID.isEmpty ()){
// Get profile data from the Data Feed.
GetDataFeed (analyticsService); // obtain data information (including "metrics" and "dimensions ")
}
} Catch (AuthenticationException e ){
System. err. println ("Authentication failed:" + e. getMessage ());
Return;
} Catch (IOException e ){
System. err. println ("Network error trying to retrieve feed :"
+ E. getMessage ());
Return;
} Catch (ServiceException e ){
System. err. println ("Analytics API responded with an error message :"
+ E. getMessage ());
Return;
}
}
/**
* Get account feed
* @ Param analyticsService
* @ Throws IOException
* @ Throws MalformedURLException
* @ Throws ServiceException
*/
Private static void getAccountFeed (AnalyticsService analyticsService)
Throws IOException, MalformedURLException, ServiceException {
// Construct query from a string.
URL queryUrl = new URL ("https://www.google.com/analytics/feeds/accounts/default? Max-results = 50 ");
// Make request to the API.
AccountFeed accountFeed = analyticsService. getFeed (queryUrl, AccountFeed. class );
// Output the data to the screen.
System. out. println ("-------- Account Feed Results --------");
For (AccountEntry entry: accountFeed. getEntries ()){
System. out. println ("\ nAccount Name ="
+ Entry. getProperty ("ga: accountName ")
+ "\ NProfile Name =" + entry. getTitle (). getPlainText () // configuration file Name
+ "\ NProfile Id =" + entry. getProperty ("ga: profileId") // configuration file Id
+ "\ NTable Id =" + entry. getTableId (). getValue (); // The Table Id of the configuration file
}
}
/**
* Obtain metrics and dimension information
* @ Param analyticsService
* @ Throws IOException
* @ Throws MalformedURLException
* @ Throws ServiceException
*/
Private static void getDataFeed (AnalyticsService analyticsService)
Throws IOException, MalformedURLException, ServiceException {
 
// Create a query using the DataQuery Object.
DataQuery query = new DataQuery (new URL ("https://www.google.com/analytics/feeds/data "));
Query. setStartDate ("2011-10-01"); // start time of the data to be counted
Query. setEndDate ("2011-10-30"); // end time of the data to be counted
Query. setDimensions ("ga: pageTitle, ga: pagePath"); // dimension information to be counted
Query. setMetrics ("ga: pageviews, ga: bounces, ga: visits, ga: visitors"); // metrics to be measured
Query. setSort ("-ga: pageviews ");
Query. setMaxResults (10 );
Query. setIds (TABLE_ID );
 
// Make a request to the API.
DataFeed dataFeed = analyticsService. getFeed (query. getUrl (),
DataFeed. class );
 
// Output data to the screen.
System. out. println ("----------- Data Feed Results ----------");
For (DataEntry entry: dataFeed. getEntries ()){
System. out. println ("\ nPage Title ="
+ Entry. stringValueOf ("ga: pageTitle") + "\ nPage Path ="
+ Entry. stringValueOf ("ga: pagePath") + "\ nPageviews ="
+ Entry. stringValueOf ("ga: pageviews") + "\ nga: bounces ="
+ Entry. stringValueOf ("ga: bounces") + "\ nga: visits access COUNT ="
+ Entry. stringValueOf ("ga: visits") + "\ nga: Number of visitors ="
+ Entry. stringValueOf ("ga: visitors "));
}
}
 
}
Finally, call the myTest () method of this class in any way (main () or servlet.
Note:
Add "ga:" before the number of Table ID, for example, ga: 47778978
The dimensions and metrics to be obtained must be set in query. setDimensions () and query. setMetrics (). See the preceding example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.