這是可以透過Google Analytics API 去抓出你網站的拜訪資料的功能,主要是送一個Request,再接收XML檔案,下面分兩段說明,首先是抓回XML的部份,:
(以下內容是參考
http://www.dotblogs.com.tw/lastsecret/archive/2010/10/06/18157.aspx )
private void GetXml() {
//送出request的網址
var request = (HttpWebRequest)HttpWebRequest.Create(
//在這是取國家的訪客數,參數可參考
http://code.google.com/intl/zh-TW/apis/analytics/docs/gdata/gdataReferenceDataFeed.html#maxResults
string.Format("https://www.google.com/analytics/feeds/data?"+
"ids=ga%3A{0}&dimensions=ga%3Acountry" +
"&metrics=ga%3Avisits&" +
"start-date={1}&end-date={2}&sort=-ga%3Avisits&max-results=10",
"12345678", //Google Analytics 網站的ID
"2011-09-24",
DateTime.Now.ToString("yyyy-MM-dd")));
//在header必須帶入token,token的取得請看下方的方法
request.Headers.Add("Authorization", "GoogleLogin auth=" + GetAuthToken());
try {
var response = request.GetResponse();
var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//抓到XML, 存到暫存資料夾
StreamWriter rd = File.CreateText(Server.MapPath("~/TempFile") + @"\Analytics_Country.xml");
rd.Write(responseContent);
rd.Flush();
} catch (Exception ex) {
Javascript.Alert(this.Page, "Error:" + ex.ToString());
}
}
private static string GetAuthToken() {
var postContent = string.Format(@"accountType=GOOGLE&Email={0}&Passwd={1}&service=analytics&source={2}",
"Account", //Google 同號
"PWD", //Google 密碼
"1234"//隨便
);
byte[] bPostData = Encoding.ASCII.GetBytes(postContent);
//參數與用法
//參考http://code.google.com/intl/zh-TW/apis/accounts/docs/AuthForInstalledApps.html
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;
var reqStream = new StreamWriter(req.GetRequestStream());
reqStream.Write(postContent);
reqStream.Flush();
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
StreamReader repStream = new StreamReader(rep.GetResponseStream(), Encoding.UTF8);
string ctx = repStream.ReadToEnd();
//送出的response抓取token的值
return Regex.Split(ctx, "Auth=", RegexOptions.IgnoreCase)[1];
}
再來是抓XML中的資料:
(以下內容是參考
http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net)
protected void GetData(object sender, EventArgs e) {
//讀XML檔案
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/TempFile") + "/Analytics_Country.xml");
XNamespace defaultSpace = xmlDoc.Root.GetDefaultNamespace();
XNamespace dxpSpace = xmlDoc.Root.GetNamespaceOfPrefix("dxp");
//LINQ XML
var datas = from entry in xmlDoc.Root.Descendants(defaultSpace + "entry")
select new {
Country = entry.Element(dxpSpace + "dimension").Attribute("value").Value,
Value = entry.Element(dxpSpace + "metric").Attribute("value").Value
};
foreach (var entry in datas) {
Response.Write("Country:" + entry.Country);
Response.Write("Visits: " + entry.Value + "<br />");
}
//datas.ToDictionary<string, int>(m => m.Country, m => m.Value);
}