2017-07-27 38 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}"); 
     } 
相關問題