Java calls Google Analytics API for website statistics

Source: Internet
Author: User

First, apply for a Google account and Google Analytics service, and put the statistics code into the website you want to count for a period of time to ensure that your Google Analytics has data.

In Google Analytics, go to your configuration file modification page and write down the red-marked number. This is your "Table ID ".

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.

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. goog Le. 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 "; // This account has the right to access the TABLE IDpublic void myTest () {try {/** System of the Google Analytics configuration file to create service objects. A service object parameter is a string that represents the application name. Then, the system uses the setUserCredentials method to process * 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); // get 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 respon Ded 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, conflict, serviceException {// Construct query from a string. URL queryUrl = new URL ("https://www.google.com/analytics/f Eeds/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 number + "\ nTable Id =" + entry. getTableId (). getValue ()); // The Table Id of the configuration file}/*** obtains 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"); // the start time of the data to be queried. setEndDate ("2011-10-30"); // query the end time of the data to be collected. setDimensions ("ga: pageTitle, ga: pagePath"); // query the dimension information to be calculated. setMetrics ("ga: pageviews, ga: bounces, ga: visits, ga: visitors"); // query the metrics to be measured. 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 views =" + 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:

  1. Add "ga:" before the number of Table ID, for example, ga: 47778978
  2. The dimensions and metrics to be obtained must be set in query. setDimensions () and query. setMetrics (). See the preceding example.
  3. For more information about dimensions and metrics, see the official Google documentation: http://code.google.com/intl/zh-CN/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html.

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.