`
qq123zhz
  • 浏览: 530781 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java连接google analytics

    博客分类:
  • java
阅读更多

 

 

    google Analytics 是google的网站分析的工具,分析的很详细,google本身提供一套展示框架。



 当然,我们可以自己制作客户端去连接google的服务器,然后取得我们所需要的数据,网上流传有flex air版的google analytics客户端,我下了一个,好像不能用,很多链接也打不开。

 看到google 提供analytics的java支持,本来想看看有没flex 的。就玩了一下下。。。

 

主程序:

 

/* Copyright (c) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.client.analytics.DataQuery;
import util.SimpleCommandLineParser;
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.ServiceException;

import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;

/**
 * Demonstrates how to use the Google Data API's Java client library to access
 * Google Analytics data.
 *
 * 
 */
public class AnalyticsClient {

  private AnalyticsClient() {}

  public static final String ACCOUNTS_URL
      = "https://www.google.com/analytics/feeds/accounts/default";

  public static final String DATA_URL = "https://www.google.com/analytics/feeds/data";

  /**
   * Returns a data feed containing the accounts that the user logged in to the
   * given AnalyticsService has access to.
   *
   * @param myService The AnalyticsService to request accounts from
   * @return An AccountFeed containing an entry for each profile the logged-in
   *     user has access to
   * @throws IOException If an error occurs while trying to communicate with
   *     the Analytics server
   * @throws ServiceException If the API cannot fulfill the user request for
   *     any reason
   */
  public static AccountFeed getAvailableAccounts(AnalyticsService myService)
      throws IOException, ServiceException {

    URL feedUrl = new URL(ACCOUNTS_URL);
    return myService.getFeed(feedUrl, AccountFeed.class);
  }

  /**
   * Displays the accounts in the given account feed.
   */
  public static void printAccounts(AccountFeed accountFeed) {
    System.out.println(accountFeed.getTitle().getPlainText());
    for (AccountEntry entry : accountFeed.getEntries()) {
      System.out.println(
          "\t" + entry.getTitle().getPlainText() + ": "
          + entry.getTableId().getValue());
    }
    System.out.println();
  }

  /**
   * Gets a very basic data query request for the given table.
   *
   * @param tableId The ID of the table to request data from
   * @return A basic query for browser, visits, and bounce information from
   *     the given table
   * @throws MalformedURLException If the URL used to request data is malformed
   */
  public static DataQuery getBasicQuery(String tableId) throws MalformedURLException {
    // Set up the request (we could alternately construct a URL manually with all query parameters
    // set)
    DataQuery query = new DataQuery(new URL(DATA_URL));
    query.setIds(tableId);
    query.setStartDate("2010-01-01");
    query.setEndDate("2010-10-31");
    query.setDimensions("ga:browser");
    query.setMetrics("ga:visits,ga:bounces");

    return query;
  }

  /**
   * Prints the contents of a data feed.
   *
   * @param title A header to print before the results
   * @param dataFeed The data feed containing data to print. Assumed to contain
   *     ga:browser, ga:visits, and ga:bounces information.
   */
  public static void printData(String title, DataFeed dataFeed) {
    System.out.println(title);
    for (DataEntry entry : dataFeed.getEntries()) {
      System.out.println("\tBrowser: " + entry.stringValueOf("ga:browser"));
      System.out.println("\t\tVisits: " + entry.stringValueOf("ga:visits"));
      System.out.println("\t\tBounces: " + entry.stringValueOf("ga:bounces"));
      System.out.println("\t\tBounce rate: "
          + entry.longValueOf("ga:bounces") / (double) entry.longValueOf("ga:visits"));
    }
    System.out.println();
  }

  /**
   * Runs through all the examples using the given GoogleService instance.
   *
   * @param myService An unauthenticated AnalyticsService object
   * @throws ServiceException If the service is unable to handle the request
   * @throws IOException If there is an error communicating with the server
   */
  public static void run(AnalyticsService myService, String username, String password)
      throws ServiceException, IOException {

    // Authenticate using ClientLogin
    myService.setUserCredentials(username, password);

    // Print a list of all accessible accounts
    AccountFeed accountFeed = getAvailableAccounts(myService);
    printAccounts(accountFeed);

    if (accountFeed.getEntries().isEmpty()) {
      return;
    }

    // Each entry in the account feed represents an individual profile
    AccountEntry profile = accountFeed.getEntries().get(0);
    String tableId = profile.getTableId().getValue();

    // Print the results of a basic request
    DataQuery basicQuery = getBasicQuery(tableId);
    DataFeed basicData = myService.getFeed(basicQuery, DataFeed.class);
    printData("BASIC RESULTS", basicData);

    // Ask Analytics to return the data sorted in descending order of visits
    DataQuery sortedQuery = getBasicQuery(tableId);
    sortedQuery.setSort("-ga:visits");
    DataFeed sortedData = myService.getFeed(sortedQuery, DataFeed.class);
    printData("SORTED RESULTS", sortedData);

    // Ask Analytics to filter out browsers that contain the word "Explorer"
    DataQuery filteredQuery = getBasicQuery(tableId);
    filteredQuery.setFilters("ga:browser!@Explorer");
    DataFeed filteredData = myService.getFeed(filteredQuery, DataFeed.class);
    printData("FILTERED RESULTS", filteredData);
    
    // Ask Analytics to filter out browsers that contain the word "Explorer"
    DataQuery regionQuery = getBasicQuery(tableId);
    filteredQuery.setFilters("ga:region!@China");
    DataFeed regionData = myService.getFeed(regionQuery, DataFeed.class);
    printData("REGION RESULTS", regionData);
  }

  /**
   * Uses the command line arguments to authenticate the GoogleService and build
   * the basic feed URI, then invokes all the other methods to demonstrate how
   * to interface with the Analytics service.
   *
   * @param args See the usage method.
   */
  public static void main(String[] args) {
	  String[] str1=new String[2];
	  str1[0]="--user=qq123zhz";
	  str1[1]="--pwd=112343";
    // Set username, password and feed URI from command-line arguments.
    SimpleCommandLineParser parser = new SimpleCommandLineParser(str1);
    String userName = parser.getValue("username", "user", "u");
    String userPassword = parser.getValue("password", "pwd", "p");
    boolean help = parser.containsKey("help", "h");
    if (help || (userName == null)) {
      usage();
      System.exit(1);
    }

    AnalyticsService myService = new AnalyticsService("exampleCo-exampleApp-1");

    try {
      run(myService, userName, userPassword);
    } catch (ServiceException se) {
      se.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

  /**
   * Prints the command line usage of this sample application.
   */
  private static void usage() {
    System.err.println("Usage: AnalyticsClient --username <username> --password <password>");
    System.err.println();
    System.err.println("Fetches and displays various pieces of "
        + "information from the Google Analytics "
        + "Data Export API.");
  }
}

 

   ACCOUNTS_URL = "https://www.google.com/analytics/feeds/accounts/default";

   DATA_URL = "https://www.google.com/analytics/feeds/data";
这两个地址分别是账号验证和ga数据存储的位置。
 
str1[0] = "--user=qq123zhz";
str1[1] = "--pwd=112343";
分别是用户名和密码,自己输入自己的google analytics帐户和密码,以上的密码被我改过了。

  query.setStartDate("2010-01-01");
    query.setEndDate("2010-10-31");
    query.setDimensions("ga:browser");
    query.setMetrics("ga:visits,ga:bounces");
 设置查询的一些参数,起始结束时间,浏览器种类,查询访问量,还有一些其他的参数。。。

 


0
0
分享到:
评论
2 楼 qq123zhz 2011-08-19  
xuzhoudeliujin 写道
下载了,不知道好使不好使

还可以。。。
1 楼 xuzhoudeliujin 2011-08-17  
下载了,不知道好使不好使

相关推荐

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

    这一步会给你一个API密钥和OAuth 2.0客户端ID,它们是Java应用连接到Google Analytics API的关键。 接着,确保你已经安装了Google的Java Client Library for Google Analytics Data API。这个库简化了与API的交互...

    google analytics demo

    跟踪ID是连接我们应用和Google Analytics服务器的关键,每个应用都应该有唯一的ID。在Android Studio项目中,我们需要添加Google Play Services库,因为Google Analytics服务包含在这个库中。这可以通过修改`build....

    Google Analytics JAR

    Google Analytics JAR文件是这个服务的一部分,通常是一个包含Java类库的压缩包,用于帮助开发者在自己的Java应用中集成Google Analytics功能。 首先,`ga_lib`目录很可能是包含了Google Analytics的Java库文件,...

    Google Analytics

    3. 获取网络载体 ID:在创建成功后,会得到一个唯一的网络载体 ID(UA-XXXXX-YY),它连接你的应用程序到 Google Analytics 帐户的配置文件。这个 ID 是追踪数据的关键,包括帐户编号和配置文件编号。 开始使用 SDK...

    ADNROID流量分析 Google_Analytics学习笔记

    Google Analytics 是一款强大的数据分析工具,由谷歌提供,用于追踪和分析网站以及移动应用的流量数据。在 Android 应用程序中集成 Google Analytics,开发者可以深入了解用户行为,优化应用性能,提高用户体验。 *...

    2legged-oauth:使用 Google Analytics Auth 时避免 url 重定向

    在Google Analytics API的上下文中,2legged OAuth被用来让应用直接代表用户获取数据,而无需用户手动进行登录或授权流程。 在使用2legged OAuth与Google Analytics API交互时,通常涉及以下几个步骤: 1. **注册...

    googleapi的jar文件

    这些JAR库包含了一系列预先编译的类和方法,使得开发者能够轻松地与Google的各种API进行交互,如Google Maps、Google Drive、Google Calendar、Google Analytics等。本文将深入探讨Google API的JAR文件,以及如何在...

    JavaAndroid优化大师源代码

    8. **分析与监控**:为了了解应用的实际运行情况,可能会集成各种分析和监控工具,如Google Analytics、Crashlytics等,以便收集性能数据,及时发现并解决问题。 9. **编译构建优化**:使用Gradle作为构建工具,...

    TesteGoogleAnalitics

    1. Google Analytics Java库:Google提供了官方的Measurement Protocol库,使得开发者能够通过Java代码发送数据到Google Analytics。例如,你可以使用HttpURLConnection或者HttpClient发送POST请求。 2. 使用 ...

    Java_课程代码库Firebase在一个周末由谷歌Android.zip

    【Java_课程代码库Firebase在一个周末由谷歌Android.zip】是一个包含与使用Firebase集成到Android应用相关的教学资源的压缩包。Firebase是由谷歌提供的一款全面的后端服务平台,它为开发者提供了实时数据库、身份...

    [myOnlinesWeb]网站在线用户信息,网站访问量

    2. **Google Analytics或其他第三方工具**:“myOnlinesWeb”也可能集成Google Analytics或其他第三方统计工具,以获取更详细的访问数据,如用户来源、设备类型、跳出率等。 3. **数据库存储**:访问量数据通常会...

    jgoogleanalyticstracker:从 code.google.compjgoogleanalyticstracker 自动导出

    这样做是为了我可以在 java gui 应用程序上使用谷歌出色的分析软件,因为谷歌从未制作过用于发送跟踪数据的 java 实现。 目前该库支持页面查看跟踪(可以有来自页面或搜索引擎的引用)和事件跟踪。 有关基本设置,...

    GAEmptyDataDemo.zip

    "GA" 可能代表“Google Analytics”或其他相关缩写,暗示这个项目可能涉及到网站或应用的数据追踪。 【描述】"GAEmptyDataDemo" 描述非常简洁,可能意味着这是一个展示如何处理“暂无数据”和“暂无网络”情况的...

    JSP流量统计系统-实现网站流量

    还可以集成第三方统计服务(如Google Analytics),以获取更丰富的用户行为数据。 通过以上步骤,我们可以构建一个基本的JSP流量统计系统,它可以实时收集和分析网站的访问数据,为网站运营提供有力支持。然而,...

    GADS_Practice_Project:GADS实践项目

    【GADS实践项目】是一个基于Java技术的综合实践项目,旨在帮助学习者深入理解和应用GADS(Google Analytics Data Studio)相关的数据处理与分析技能。在这个项目中,你将有机会运用Java编程语言,结合数据分析工具,...

    [myOnlinesWeb2]网站在线用户信息,网站访问量以及管理员踢出用户实例

    还可以使用Google Analytics或其他第三方服务,通过JavaScript代码嵌入到网页中收集数据,提供更详细的用户行为分析。 5. **管理员权限控制** 管理员踢出用户功能涉及到权限管理。项目可能采用了角色-权限模型,...

    一个企业站点

    9. **数据分析**:利用Google Analytics或其他分析工具监控网站流量,了解用户行为,持续优化网站性能。 10. **社交媒体整合**:将企业站点与微信、微博等社交平台连接,扩大影响力,提高用户参与度。 此外,"另类...

    中小型企业网站

    9. **数据分析**:通过Google Analytics等工具收集网站访问数据,分析用户行为,为优化策略提供依据。 10. **维护与更新**:定期更新网站内容、修复漏洞、安装补丁以保持网站的最新状态和安全性。 11. **电子商务...

Global site tag (gtag.js) - Google Analytics