2011-04-25 230 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