2017-07-27 69 views
1

我试图从WPF应用程序向Google Analytics发送数据。我无法在网上找到任何明确定义如何执行此操作的资源。我知道有很多NuGet软件包可用,但我不确定要使用哪种软件包,也不知道如何实施它们。我也知道有一些第三方的“帮手”库可用(请参阅Using Google Analytics from a .NET desktop application),我不感兴趣。它看起来像大多数在线指令显示如何从GA中“拉”数据,而不是如何推送。不是在寻找“可能”或变通方法,而是寻求这种正常简单的方法。这应该不复杂。只需要一个“Hello World”。从WPF向Google Analytics提交数据

你能指点我正确的方向吗?谢谢,

+0

你应该看看[测量协议(https://developers.google.com/analytics/devguides/collection/protocol/v1/)。它允许您通过简单的HTTP请求向Google Analytics发送数据,无论您使用何种语言,它都必须具有http请求库。查看[命中生成器工具](https://ga-dev-tools.appspot.com/hit-builder/)查看如何验证请求。 – Matt

回答

0

这为我工作:

 var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect"); 
     request.Method = "POST"; 

     // the request body we want to send 
     var postData = new Dictionary<string, string> 
        { 
         { "v", "1" }, //analytics protocol version 
         { "tid", "UA-XXXXXXXX-X" }, //analytics tracking property id 
         { "cid", "XXXX"}, //unique user identifier 
         { "t", "event" }, //event type 
         { "ec", category }, 
         { "ea", action }, 
        }; 

     var postDataString = postData 
      .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key, 
                 Uri.EscapeDataString(next.Value))) 
      .TrimEnd('&'); 

     // set the Content-Length header to the correct value 
     request.ContentLength = Encoding.UTF8.GetByteCount(postDataString); 

     // write the request body to the request 
     using (var writer = new StreamWriter(request.GetRequestStream())) 
     { 
      writer.Write(postDataString); 
     } 

     var webResponse = (HttpWebResponse)request.GetResponse(); 
     if (webResponse.StatusCode != HttpStatusCode.OK) 
     { 
      throw new Exception($"Google Analytics tracking did not return OK 200. Returned: {webResponse.StatusCode}"); 
     } 
相关问题