2011-04-25 228 views
2

我想用C#代碼代替JavaScript代碼對谷歌分析谷歌Analytics(分析)在C#

<script type="text/javascript"> 
     var _gaq = _gaq || []; 
     _gaq.push(['_setAccount', 'UA-xxxxxxx-x']); 
     _gaq.push(['_trackPageview']); 
     (function() { 
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; 
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); 
     })(); 

C#

var query = HttpUtility.ParseQueryString(String.Empty); 
     query.Add("utmwv", "4.9"); 
     query.Add("utmhn", "host name"); 
     query.Add("utmcs", "UTF-8"); 
     query.Add("utmul", "en-us"); 
     query.Add("utmdt", "google analysis... c#"); 
     query.Add("utmac", "UA-xxxxxx-x"); 
     string m = "http://www.google-analytics.com/__utm.gif?"; 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m); 
     request.Method = "POST"; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.Headers.Add("GData-Version", "2"); 
    var uri = new UriBuilder("http://www.google-analytics.com/__utm.gif?"); 
     uri.Query = query.ToString(); 


     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.ToString()); 
     request.Method = "POST"; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.Headers.Add("GData-Version", "2"); 
     byte[] data = Encoding.ASCII.GetBytes(query.ToString()); 
     Stream input = request.GetRequestStream(); 
     input.Write(data, 0, data.Length); 
     input.Close(); 
     HttpWebResponse nsResponse = (HttpWebResponse)request.GetResponse(); 
     Stream streamResponse = nsResponse.GetResponseStream(); 
     StreamReader streamRead = new StreamReader(streamResponse); 
     string responseString = streamRead.ReadToEnd(); 

上面的代碼,我想提出一個web請求,但都無濟於事。我錯過了什麼,或者更好的方法嗎?

+0

什麼是你得到的錯誤/ HTTP返回代碼? (假設你真的看到了響應) – BrokenGlass 2011-04-25 14:37:24

+0

我收到了這個響應,沒有流量對谷歌分析。「GIF89a \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0,\ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0D \ 0;」 – Hidsman 2011-04-25 15:31:40

+0

@Hidsman這個返回值是「GIF89a \ 0 \0 \0 \ 0 \ 0 \ 0,\ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0D \ 0;」好。因爲它將gif圖像作爲響應返回。 :) – DevT 2012-10-12 03:48:49

回答

-1

它應該是GET請求而不是POST。不知道這是否有所作爲,但在上面的例子中你肯定錯過了很多參數。您應該使用類似Firebug或Live HTTP Headers的內容來查看發送給Google Analytics的內容並模仿該內容。

我也看不到在您的代碼中添加到請求中的查詢,但也許您沒有在此處發佈該位。

+0

我確實嘗試過這兩個帖子並獲得。沒有錯誤。在resposne我得到「GIF89a \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0,\ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0D \ 0;」但第二天googla分析沒有流量。 – Hidsman 2011-04-25 19:37:10

+0

這並沒有幫助我。 =( – Ryan 2013-11-09 01:02:54