- 浏览: 72882 次
- 性别:
- 来自: 北京
-
文章分类
最新评论
JAVA 下载Google Analytics 数据简单Demo
采用JAVA 获取google analytics产生的流量检测数据。
配置:JDK5.0及以上
GoogleAnalytics.java package com.cms.util; // Copyright 2010 Google Inc. All Rights Reserved. /* 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 com.google.gdata.data.analytics.DataFeed; import com.google.gdata.util.AuthenticationException; import com.google.gdata.util.ServiceException; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; /** * This application demos the "AnalyticsCsvPrinter" class, which converts a * response from the Data Export API into CSV format. * * @author api.alexl@google.com (Alexander Lucas) */ public class GoogleAnalytics { private static final String CLIENT_USERNAME = "test.ga@gmail.com";//邮箱帐号 private static final String CLIENT_PASS = "123456";//PASSWORD private static final String TABLE_ID = "ga:67972528";//配置ID private static AnalyticsCsvPrinter printer = new AnalyticsCsvPrinter(); /** * Grabs the response feed and prints it in CSV format * to standard output. * @param args Command Line Arguments. */ public static void main(String[] args) { System.out.println("come..."); DataFeed feed = getDataFeed(getAnalyticsService("cvs_printing_demo"), getDataQuery()); if(args.length > 0) { printFeedToFile(feed, args[0]); } else { // If no output stream is set, the default is to print to stdout. printer.printFeedAsCsv(feed); } } /** * Opens a write stream to a file, and sets that as the output stream for the * printer object that prints the feed. * @param feed The DataFeed to convert to CSV format. * @param filename The filename to be written to. */ private static void printFeedToFile(DataFeed feed, String filename) { PrintStream stream = null; try { FileOutputStream fstream = new FileOutputStream(filename); stream = new PrintStream(fstream); printer.setPrintStream(stream); printer.printFeedAsCsv(feed); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } finally { if (stream != null) { stream.flush(); stream.close(); } } } /** * Creates and returns a new AnalyticsService object and authorizes the user using * Client Login. * @return AnalyticsService to be used */ private static AnalyticsService getAnalyticsService(String clientName) { try { AnalyticsService analyticsService = new AnalyticsService(clientName); analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS); System.out.println("login ok..."); return analyticsService; } catch (AuthenticationException e) { System.err.println("Authentication failed : " + e.getMessage()); System.exit(-1); } return null; } /** * Creates and returns the default DataQuery. * * @return AnalyticsService to be used */ private static DataQuery getDataQuery() { DataQuery query = null; try { // Create a query using the DataQuery Object. query = new DataQuery(new URL( "https://www.google.com/analytics/feeds/data")); query.setStartDate("2012-01-01"); query.setEndDate("2013-04-30"); query.setDimensions("ga:pageTitle,ga:pagePath"); query.setMetrics("ga:visits,ga:pageviews"); query.setSort("-ga:pageviews"); query.setMaxResults(10); query.setIds(TABLE_ID); System.out.println("Query..."); } catch (MalformedURLException e) { System.err.println("Error, malformed URL: " + e.getMessage()); System.exit(-1); } return query; } /** * Makes the actual request to the server. * * @param analyticsService Google Analytics service object that * is authorized through Client Login. * @param query the query being sent to the Data Export API. * @returns the responds from the Data Export API. */ private static DataFeed getDataFeed(AnalyticsService analyticsService, DataQuery query) { DataFeed dataFeed = null; try { // Make a request to the API. dataFeed = analyticsService.getFeed(query.getUrl(), DataFeed.class); } catch (IOException e) { System.err.println("Network error trying to retrieve feed: " + e.getMessage()); System.exit(-1); } catch (ServiceException e) { System.err.println("Analytics API responded with an error message: " + e.getMessage()); System.exit(-1); } return dataFeed; } } AnalyticsCsvPrinter.java package com.cms.util; //Copyright 2010 Google Inc. All Rights Reserved. /* 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.data.analytics.DataEntry; import com.google.gdata.data.analytics.DataFeed; import com.google.gdata.data.analytics.Dimension; import com.google.gdata.data.analytics.Metric; import java.io.PrintStream; import java.util.Iterator; /** * A class which converts a DataFeed object into a series of data rows in the * CSV format. * * @author api.alexl@google.com (Alexander Lucas) */ public class AnalyticsCsvPrinter { private PrintStream printStream = System.out; /** * Returns the output stream this object will write output to. * * @return The output stream this object will write output to. */ public PrintStream getPrintStream() { return printStream; } /** * Sets the output stream this object will write output to. * * @param printStream The output stream this object will write output to. */ public void setPrintStream(PrintStream printStream) { this.printStream = printStream; } /** * Prints the contents of a Data Feed in CSV format, to the output stream * specified using "setPrintStream". Uses System.out by default. This * method prints row headers. To print multiple queries to one output, one * can also use "printEntries", which does not print row headers. * * @param feed The feed whose contents are printed in CSV format. */ public void printFeedAsCsv(DataFeed feed) { printRowHeaders(feed); printBody(feed); } /** * Prints all the entries in a feed in CSV format. Does *not* print * row headers. * * @param feed The feed whose contents are printed in CSV format. */ public void printBody(DataFeed feed) { if(feed.getEntries().size() == 0) { return; } for (DataEntry entry : feed.getEntries()) { printEntry(entry); } } /** * Prints all the values in a data feed entry in CSV format. * * @param entry The data entry whose contents are printed in CSV format. */ public void printEntry(DataEntry entry) { Iterator<Dimension> dimensions = entry.getDimensions().iterator(); while (dimensions.hasNext()) { printStream.print(sanitizeForCsv(dimensions.next().getValue())); printStream.print(","); } Iterator<Metric> metrics = entry.getMetrics().iterator(); while (metrics.hasNext()) { printStream.print(sanitizeForCsv(metrics.next().getValue())); if (metrics.hasNext()) { printStream.print(","); } } printStream.println(); } /** * Prints the row headers (column names) of a feed. * * @param feed The feed whose row headers are to be printed. */ public void printRowHeaders(DataFeed feed) { if(feed.getEntries().size() == 0) { return; } DataEntry firstEntry = feed.getEntries().get(0); Iterator<Dimension> dimensions = firstEntry.getDimensions().iterator(); while (dimensions.hasNext()) { printStream.print(sanitizeForCsv(dimensions.next().getName())); printStream.print(","); } Iterator<Metric> metrics = firstEntry.getMetrics().iterator(); while (metrics.hasNext()) { printStream.print(sanitizeForCsv(metrics.next().getName())); if (metrics.hasNext()) { printStream.print(","); } } printStream.println(); } /** * Modifies a string so that it is a valid cell in a CSV document. * Note that this method works on a single value, not a whole row of data. * * @param cellData The string to be made CSV-compatible. * @return a version of the string which works as a single CSV cell. */ private String sanitizeForCsv(String cellData) { // Since most sanitizing will involve wrapping the string in double quotes, // check and see if double quotes that are part of the string value already exist. // If they do, escape them. Escaping a double quote is done by placing an // extra one right next to it, so " becomes "". StringBuilder resultBuilder = new StringBuilder(cellData); int lastIndex = 0; while (resultBuilder.indexOf("\"", lastIndex) >= 0) { int quoteIndex = resultBuilder.indexOf("\"", lastIndex); resultBuilder.replace(quoteIndex, quoteIndex + 1, "\"\""); lastIndex = quoteIndex + 2; } // Several conditions are solved by wrapping the value in double quotes. // Since this should only happen once per escaped string, we can check // for all conditions simultaneously. The conditions are: // -Comma in the cellData value // -Line break in the cellData value // -Leading or trailing whitespace in the celldata value char firstChar = cellData.charAt(0); char lastChar = cellData.charAt(cellData.length() - 1); if (cellData.contains(",") || cellData.contains("\n") || Character.isWhitespace(firstChar) || Character.isWhitespace(lastChar)) { resultBuilder.insert(0, "\"").append("\""); } return resultBuilder.toString(); } }
提供一个Demo下载地址:http://download.csdn.net/detail/thl331860203/5072926
相关推荐
本文将深入探讨如何使用Java来调用Google Analytics API,实现对网站数据的统计分析。 首先,你需要在Google Cloud Console上创建一个新的项目,并启用Google Analytics API。这一步会给你一个API密钥和OAuth 2.0...
在这个"google analytics demo"中,我们将探讨如何在Android应用程序中集成Google Analytics服务,以及如何通过分析数据来改进应用性能。 首先,我们需要在Google Analytics官网创建一个账户并获取跟踪ID。跟踪ID是...
在`GoogleAnalyticsDemo`中,你可以看到如何在Java代码中触发这些事件并发送数据到Google Analytics服务器。 **页面视图跟踪**:当用户访问一个新的页面时,你应该发送一个页面视图事件。这有助于了解用户在应用中...
Cordova-Google-Analytics-Demo Demo Phonegap App 使用 Google Analytics 实现,它将帮助那些想要将 Google Analytics 集成到他们的 phonegap 移动应用程序中的人。 我们在此应用程序中使用了phonegap 插件。 在...
5. **Google服务接口调用**:可能包含的API包括但不限于Google Maps、Google Drive、Google Sheets、Google Calendar、Google Analytics、Google Cloud Storage等。源码会演示如何初始化API客户端,调用不同的服务...
标题“ANE-Google-Analytics-Demo”涉及到的是一个使用ActionScript开发的示例项目,它主要目的是演示如何在Android和iOS设备上集成并使用Google Analytics服务。ActionScript是一种基于ECMAScript的脚本语言,常见...
2. 数据分析:通过Google Analytics、Flurry等工具跟踪用户行为,优化功能和用户体验。 3. 更新迭代:根据反馈和数据分析结果,定期更新和修复问题。 以上就是与“app demo”相关的IT知识要点,涵盖了从开发、设计...
10. **数据分析**:通过Google Analytics或其他工具收集用户行为数据,以优化用户体验和提高用户留存率。 综上所述,"仿新闻类demo"是一个包含多种技术栈和设计考量的项目,旨在创建一个功能完善的新闻信息平台。...
Google Java API客户端服务 此存储库包含使用各个API的生成的源。 我们建议使用的身份来处理身份验证。 要求 Java 7(或更高版本) Android 1.6(或更高版本) 支持的Google API 您可以在下面找到可用API的列表,...
此演示使用 Google Analytics Java API 和在 Google Earth 地图上呈现访问者统计信息。 为了使用此项目为您自己的 Google Analytics 帐户呈现统计信息,您需要: 在以下位置创建一个名为 config.properties 的文件...
8. **数据分析**:后台可能集成了数据分析模块,如Google Analytics或自建的数据统计系统,对用户行为、销售额等进行统计分析,为企业决策提供数据支持。 这个压缩包提供了一个企业级电商系统的实例,对于学习小...
系统可集成数据分析工具,如Google Analytics,以了解用户行为,优化销售策略。还可以实现邮件订阅、促销推送等功能,增强营销效果。 总结,"bookseller2007demo"是一个全面的购书网络系统,涵盖从用户购物到后台...
9. **数据分析**:利用Google Analytics或其他分析工具监控网站流量,了解用户行为,持续优化网站性能。 10. **社交媒体整合**:将企业站点与微信、微博等社交平台连接,扩大影响力,提高用户参与度。 此外,"另类...
According to Google Trends, Python’s interest over time has been steadily rising, while the interest in Java and Delphi has been declining. This trend indicates that Python is becoming the go-to ...