首先,需要认证您的账户:
。。。
protected static string token = "";
。。。
protected static void Login() {
string accountType = "accountType";
string email = System.Configuration.ConfigurationManager.AppSettings.Get("GoogleAccount");
string pwd = System.Configuration.ConfigurationManager.AppSettings.Get("GoogleAccountPwd");
string service = "analytics";
string source = System.Configuration.ConfigurationManager.AppSettings.Get("GASource");
string postData = "accountType=" + accountType
+ "&Email=" + email
+ "&Passwd=" + pwd
+ "&service=" + service
+ "&source=" + source;
byte[] bPostData = Encoding.ASCII.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/accounts/ClientLogin");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bPostData.Length;
。。。
protected static string token = "";
。。。
protected static void Login() {
string accountType = "accountType";
string email = System.Configuration.ConfigurationManager.AppSettings.Get("GoogleAccount");
string pwd = System.Configuration.ConfigurationManager.AppSettings.Get("GoogleAccountPwd");
string service = "analytics";
string source = System.Configuration.ConfigurationManager.AppSettings.Get("GASource");
string postData = "accountType=" + accountType
+ "&Email=" + email
+ "&Passwd=" + pwd
+ "&service=" + service
+ "&source=" + source;
byte[] bPostData = Encoding.ASCII.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/accounts/ClientLogin");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bPostData.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bPostData, 0, bPostData.Length);
reqStream.Close();
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
StreamReader repStream = new StreamReader(rep.GetResponseStream(), Encoding.UTF8);
string ctx = repStream.ReadToEnd();
token = Regex.Split(ctx, "Auth=", RegexOptions.IgnoreCase)[1];
}
Google API 提供三种认证方法:
AuthSub proxy authentication
OAuth authentication for web applications
ClientLogin username/password authentication
我采用的是 ClientLogin 方法。
这里有几个参数需要注意:
service 和 accountType, source 这三个参数需要注意,不过,我上面的代码可能和GOOGLE给出的不一样(也是从GOOGLE示例代码里看到的),不影响使用。
service 的取值可以从这里得到:http://code.google.com/support/bin/answer.py?answer=62712&topic=10433
source 就如GOOGLE写的:A string identifying your client application in the form companyName-applicationName-versionID 只是一个标志,你想给什么就给什么。
如果认证成功,在 Response 里会包含一个 Auth ,你只要把这个 Auth 的值保存下来就是了。我是把它保存在 token 里了。这个 token非常重要,每次请求数据,你都要把这
个 token 发送出去,用以判断您是不是合法的用户。
二,按日期取数据:
private static void GetClicksGroupByTimeMode(TimeMode tm, int retailerID, DateTime dateS, DateTime dateE, out int pageView, out int uniqueView, out
Dictionary<string, int[]> entriesData) {
if (token == "") {
Login();//如果没登陆,token就是空的,需要先登陆。
}
string dimensions, sort,flag;
switch (tm) {
case TimeMode.date:
dimensions = "ga:date";
sort = "ga:date";//按 date 排序
flag = "ga:date";
break;
case TimeMode.month:
dimensions = "ga:month";
sort = "ga:month";
flag = "ga:month";
break;
case TimeMode.week:
dimensions = "ga:week";
sort = "ga:week";
flag = "ga:week";
break;
case TimeMode.year:
dimensions = "ga:year";
sort = "ga:year";
flag = "ga:year";
break;
default:
dimensions = "ga:date";
sort = "ga:date";
flag = "ga:date";
break;
}
string metrics = "ga:pageviews,ga:uniquePageviews";//要取出的数据
if (dateS > dateE) {//日期的顺序一定不能弄反,google 不会给你调整的
DateTime t = dateS;
dateS = dateE;
dateE = t;
}
string endDate = dateE.ToString("yyyy-MM-dd");
string startDate = dateS.ToString("yyyy-MM-dd");
//string filter = "ga:pagePath" + Uri.EscapeDataString("=~&") + "rid" + Uri.EscapeDataString("=") + retailerID;
string filter = "ga:pagePath" + Uri.EscapeDataString("=~") + "/Responseredirect.aspx" + ";ga:pagePath" + Uri.EscapeDataString("=~&") + "rid" +
Uri.EscapeDataString("=") + retailerID + Uri.EscapeDataString("&");
if(retailerID == -1)
filter = "ga:pagePath" + Uri.EscapeDataString("=~") + "/Responseredirect.aspx" + ";ga:pagePath" + Uri.EscapeDataString("=~&") + "rid" +
Uri.EscapeDataString("=");
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/analytics/feeds/data?ids=ga:" + gaId + "&dimensions=" + dimensions
+ "&metrics=" + metrics + "&filters=" + filter + "&sort=" + sort + "&start-date=" + startDate + "&end-date=" + endDate);
req.Headers.Add("Authorization", "GoogleLogin auth=" + token);
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
XmlDocument doc = new XmlDocument();
XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
xnm.AddNamespace("dxp", "http://schemas.google.com/analytics/2009");
xnm.PushScope();
xnm.AddNamespace("GA", "http://www.w3.org/2005/Atom");
doc.Load(rep.GetResponseStream());
XmlNode node = doc.SelectSingleNode("//dxp:aggregates/dxp:metric[@name='ga:uniquePageviews']", xnm);
uniqueView = int.Parse(node.Attributes.GetNamedItem("value").Value);
node = doc.SelectSingleNode("//dxp:aggregates/dxp:metric[@name='ga:pageviews']", xnm);
pageView = int.Parse(node.Attributes.GetNamedItem("value").Value);
entriesData = new Dictionary<string, int[]>();
XmlNode sub;
string entryFlag;
int entryPageView, entryUniqueView;
XmlNodeList entries = doc.SelectNodes("//GA:entry", xnm);
foreach (XmlNode entry in entries) {
sub = entry.SelectSingleNode("dxp:dimension[@name='" + flag + "']", xnm);
//entryDate = DateTime.ParseExact(sub.Attributes.GetNamedItem("value").Value, "yyyyMMdd", null);
entryFlag = sub.Attributes.GetNamedItem("value").Value;
sub = entry.SelectSingleNode("dxp:metric[@name='ga:pageviews']", xnm);
entryPageView = int.Parse(sub.Attributes.GetNamedItem("value").Value);
sub = entry.SelectSingleNode("dxp:metric[@name='ga:uniquePageviews']", xnm);
entryUniqueView = int.Parse(sub.Attributes.GetNamedItem("value").Value);
entriesData.Add(entryFlag, new int[] { entryPageView, entryUniqueView });
}
注意:dimensions, sort , metrics , filter
dimension 就是指哪种报告,ga:week 就是指 按周报告, ga:pagePath 是指按地址报告,具体的可以从这里找出:
http://code.google.com/intl/zh-CN/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
metrics 就是返回的数据里具体包含哪些字段。ga:pageviews,ga:uniquePageviews 就是指返回唯总访问量和唯一(跟据IP)访问量。
sort 是按什么标准排序。可以是 ga:date或ga:week,ga:pageViews等。如果有多个排序标准,用逗号间隔。如果是倒序,就加个负号: ga:date,-ga:pageView
另外,sort 好像只能是 dimension 和 metrics 中列出的字段。如果不是列出的列段,会报401错误。
filter 是条件,
filter = "ga:pagePath" + Uri.EscapeDataString("=~") + "/Responseredirect.aspx" + ";ga:pagePath" + Uri.EscapeDataString("=~&") + "rid" + Uri.EscapeDataString("=");
=~ 的意思就是包含,具体请参见:http://code.google.com/intl/zh-CN/apis/analytics/docs/gdata/gdataReference.html#filtering
如果 filter 是 and 两个条件之间用 ; 分隔。如果是 or 则用 , 分隔。
其它的还有:
start-date, end-date 开始日期和结束日期,
start-index 从排序、条件查询后,第多少条开始返回
max-results 每次返回多少条
dimension 和 metrics 的结合是有限制的,不是随便搭配的,具体的描述起来太麻烦,我也只是用到才看,如果需要可以从这里找:
http://code.google.com/intl/zh-CN/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
| < Prev | Next > |
|---|
Last Updated ( Wednesday, 08 July 2009 22:28 )



