c# – Google AnalyticsAPI – 以编程方式在服务器端获取网页浏览量

前端之家收集整理的这篇文章主要介绍了c# – Google AnalyticsAPI – 以编程方式在服务器端获取网页浏览量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们有一个由几个页面组成的Web应用程序.我们已将我们的网络应用域注册到Google Analytics,并且网页浏览量跟踪按预期工作(在Google Analytics面板中,我们可以看到每个网页的网页浏览量).现在我们希望此页面视图信息存储在我们的DB内部的后端.因此,我们希望创建一个每天运行一次的后端流程,并从Analytics API中获取页面视图.

这当然需要在代码中完成.从最初的研究看来,为了访问Analytics API,必须进行身份验证过程,这意味着人类用户必须输入id和密码.

问题是,它只能用代码完成吗?

解决方法

//-------------- Get Auth Token -------------------

    WebClient webClient = new WebClient();
    NameValueCollection data = new NameValueCollection();
    data.Add("accountType","GOOGLE");
    data.Add("Email","xxxx@gmail.com");
    data.Add("Passwd","xxxx");//Passwd,not a misspell.
    data.Add("service","analytics");
    data.Add("source","xxxx-xxxx-xx");//Could be anything.

    byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin","POST",data);
    string tokens = Encoding.UTF8.GetString(bytes);
    string authToken = extractAuthToken(tokens);

    //-------------- Get page views -------------------

    string Feed = "https://www.google.com/analytics/Feeds/data";

    //required:
    string ids = "ga:xxxx";
    string metrics = "ga:pageviews";
    string startDate = "2011-06-25";
    string endDate = "2011-07-25";

    //Optional:
    string dimensions = "ga:pagePath";
    string sort = "-ga:pageviews";            

    string FeedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",Feed,ids,dimensions,metrics,sort,startDate,endDate);

    webClient.Headers.Add("Authorization","GoogleLogin " + authToken);
    string result = webClient.DownloadString(FeedUrl);

    //-------------- Extract data from xml -------------------

    XDocument xml = XDocument.Parse(result);
    var ns1 = "{http://www.w3.org/2005/Atom}";
    var ns2 = "{http://schemas.google.com/analytics/2009}";

    var q = from entry in xml.Descendants()
            where entry.Name == ns1 + "entry"
            select new
            {
                PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,Views = entry.Element(ns2 + "metric").Attribute("value").Value
            };

    //-------------- Do something with data -------------------
    foreach (var page in q)
    {
        Debug.WriteLine(page.PagePath + " " + page.Views);                
    }

    //-------------- Help Method -------------------
    private string extractAuthToken(string data)
    {          
        var tokens = data.Split(new string[] { "\n" },StringSplitOptions.RemoveEmptyEntries);            
        return tokens.Where(token => token.StartsWith("Auth=")).Single();
    }
原文链接:https://www.f2er.com/csharp/244056.html

猜你在找的C#相关文章