Java调用Google Analytics API实现网站统计

来源:互联网 发布:春秋航空 知乎 编辑:程序博客网 时间:2024/06/07 00:30

  首先,申请Google帐号和Google Analytics服务,并将统计代码放入你想统计的网站中一段时间,确保你的Google Analytics中已有数据。

    在Google Analytics中,进入你的配置文件修改界面,如图,记下红色标记的数字,这是你的“Table ID”。


下面代码是我根据Google官方文档修改并注释的一段代码,就可以实现访问量等信息的统计了。

[java] view plaincopyprint?
  1. package cn.edu.KFC.bean;  
  2.   
  3. import com.google.gdata.client.analytics.AnalyticsService;  
  4. import com.google.gdata.client.analytics.DataQuery;  
  5. import com.google.gdata.data.analytics.AccountEntry;  
  6. import com.google.gdata.data.analytics.AccountFeed;  
  7. import com.google.gdata.data.analytics.DataEntry;  
  8. import com.google.gdata.data.analytics.DataFeed;  
  9.   
  10. import com.google.gdata.util.AuthenticationException;  
  11. import com.google.gdata.util.ServiceException;  
  12.   
  13. import java.io.IOException;  
  14. import java.net.MalformedURLException;  
  15. import java.net.URL;  
  16.   
  17.   
  18. public class GoogleAnalytics {  
  19.     // 使用ClientLogin 方法访问Google Analytics。其中,两个常量分别存储用户名和密码。  
  20.     private static final String CLIENT_USERNAME = "anyone@gmail.com"//Google 帐号  
  21.     private static final String CLIENT_PASS = "1234567";  //Google 密码  
  22.     private static final String TABLE_ID = "ga:715123"//此帐号有权访问的Google Analytics配置文件的TABLE ID  
  23.   
  24.     public void myTest() {  
  25.         try {  
  26.             /* 
  27.              * 系统创建服务对象。服务对象的参数是一个代表应用程序名称的字符串。随后,系统将采用 setUserCredentials 方法来处理 
  28.              * Google Analytics(分析)授权。 
  29.              */  
  30.             // Service Object to work with the Google Analytics Data Export API.  
  31.             AnalyticsService analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");  
  32.             // Client Login Authorization.   
  33.             analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);  
  34.   
  35.             // Get data from the Account Feed.  
  36.             getAccountFeed(analyticsService);  //获取帐号信息  
  37.   
  38.             // Access the Data Feed if the Table Id has been set.  
  39.             if (!TABLE_ID.isEmpty()) {  
  40.                 // Get profile data from the Data Feed.  
  41.                 getDataFeed(analyticsService);  //获取数据信息(包括"指标"和"维度")  
  42.             }  
  43.   
  44.         } catch (AuthenticationException e) {  
  45.             System.err.println("Authentication failed : " + e.getMessage());  
  46.             return;  
  47.         } catch (IOException e) {  
  48.             System.err.println("Network error trying to retrieve feed: "  
  49.                     + e.getMessage());  
  50.             return;  
  51.         } catch (ServiceException e) {  
  52.             System.err.println("Analytics API responded with an error message: "  
  53.                             + e.getMessage());  
  54.             return;  
  55.         }  
  56.     }  
  57.   
  58.     /** 
  59.      * 获取帐号feed 
  60.      * @param analyticsService 
  61.      * @throws IOException 
  62.      * @throws MalformedURLException 
  63.      * @throws ServiceException 
  64.      */  
  65.     private static void getAccountFeed(AnalyticsService analyticsService)  
  66.             throws IOException, MalformedURLException, ServiceException {  
  67.   
  68.         // Construct query from a string.   
  69.         URL queryUrl = new URL("https://www.google.com/analytics/feeds/accounts/default?max-results=50");  
  70.   
  71.         // Make request to the API.   
  72.         AccountFeed accountFeed = analyticsService.getFeed(queryUrl, AccountFeed.class);  
  73.   
  74.         // Output the data to the screen.   
  75.         System.out.println("-------- Account Feed Results --------");  
  76.         for (AccountEntry entry : accountFeed.getEntries()) {  
  77.             System.out.println("\nAccount Name  = "  
  78.                     + entry.getProperty("ga:accountName")  
  79.                     + "\nProfile Name  = " + entry.getTitle().getPlainText()  //配置文件名称  
  80.                     + "\nProfile Id    = " + entry.getProperty("ga:profileId")  //配置文件编号  
  81.                     + "\nTable Id      = " + entry.getTableId().getValue());   //配置文件的Table Id  
  82.         }  
  83.     }  
  84.   
  85.     /** 
  86.      * 获取指标和维度信息 
  87.      * @param analyticsService 
  88.      * @throws IOException 
  89.      * @throws MalformedURLException 
  90.      * @throws ServiceException 
  91.      */  
  92.     private static void getDataFeed(AnalyticsService analyticsService)  
  93.             throws IOException, MalformedURLException, ServiceException {  
  94.   
  95.         // Create a query using the DataQuery Object.  
  96.         DataQuery query = new DataQuery(new URL("https://www.google.com/analytics/feeds/data"));  
  97.         query.setStartDate("2011-10-01");  //要统计的数据的起始时间  
  98.         query.setEndDate("2011-10-30");  //要统计的数据的结束时间  
  99.         query.setDimensions("ga:pageTitle,ga:pagePath");   //要统计的维度信息  
  100.         query.setMetrics("ga:pageviews,ga:bounces,ga:visits,ga:visitors");  //要统计的指标信息  
  101.         query.setSort("-ga:pageviews");    
  102.         query.setMaxResults(10);  
  103.         query.setIds(TABLE_ID);  
  104.   
  105.         // Make a request to the API.   
  106.         DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),  
  107.                 DataFeed.class);  
  108.   
  109.         // Output data to the screen.   
  110.         System.out.println("----------- Data Feed Results ----------");  
  111.         for (DataEntry entry : dataFeed.getEntries()) {  
  112.             System.out.println("\nPage Title = "  
  113.                     + entry.stringValueOf("ga:pageTitle") + "\nPage Path  = "  
  114.                     + entry.stringValueOf("ga:pagePath") + "\nPageviews浏览量  = "  
  115.                     + entry.stringValueOf("ga:pageviews") + "\nga:bounces = "  
  116.                     + entry.stringValueOf("ga:bounces") + "\nga:visits访问次数 = "  
  117.                     + entry.stringValueOf("ga:visits") + "\nga:visitors访问人数 = "  
  118.                     + entry.stringValueOf("ga:visitors"));  
  119.         }  
  120.     }  
  121.   
  122. }  
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 {// 使用ClientLogin 方法访问Google Analytics。其中,两个常量分别存储用户名和密码。private static final String CLIENT_USERNAME = "anyone@gmail.com"; //Google 帐号private static final String CLIENT_PASS = "1234567";  //Google 密码private static final String TABLE_ID = "ga:715123"; //此帐号有权访问的Google Analytics配置文件的TABLE IDpublic void myTest() {try {/* * 系统创建服务对象。服务对象的参数是一个代表应用程序名称的字符串。随后,系统将采用 setUserCredentials 方法来处理 * Google Analytics(分析)授权。 */// 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);  //获取帐号信息// Access the Data Feed if the Table Id has been set.if (!TABLE_ID.isEmpty()) {// Get profile data from the Data Feed.getDataFeed(analyticsService);  //获取数据信息(包括"指标"和"维度")}} 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;}}/** * 获取帐号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()  //配置文件名称+ "\nProfile Id    = " + entry.getProperty("ga:profileId")  //配置文件编号+ "\nTable Id      = " + entry.getTableId().getValue());   //配置文件的Table Id}}/** * 获取指标和维度信息 * @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");  //要统计的数据的起始时间query.setEndDate("2011-10-30");  //要统计的数据的结束时间query.setDimensions("ga:pageTitle,ga:pagePath");   //要统计的维度信息query.setMetrics("ga:pageviews,ga:bounces,ga:visits,ga:visitors");  //要统计的指标信息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访问次数 = "+ entry.stringValueOf("ga:visits") + "\nga:visitors访问人数 = "+ entry.stringValueOf("ga:visitors"));}}}

最后,使用任意方式(main()或servlet)调用这个class的myTest()方法即可。

注意:

  1. Table ID的数字前加上“ga:”,例如ga:47778978
  2. 要取得的维度和指标信息需要在query.setDimensions()和query.setMetrics()中设定一下,见上面例子。
  3. 维度和指标具体含义,见Google官方文档:http://code.google.com/intl/zh-CN/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
原创粉丝点击