从WPF向Google Analytics提交数据

时间:2017-07-27 13:50:06

标签: wpf google-analytics google-analytics-api

我正在尝试从WPF应用程序向Google Analytics发送数据。我无法在线找到任何明确定义如何操作的资源。我知道有很多可用的NuGet包,但我不确定使用哪个,也不知道如何实现它们。我也知道有一些第三方"帮手"可用的图书馆(请参阅Using Google Analytics from a .NET desktop application),我对此不感兴趣。看起来大多数在线说明都显示如何“拉动”#34;来自GA的数据,而不是如何推送。不寻找"可能"或变通方法,但正常的直接方式是什么。这不应该是复杂的。只需要一个" Hello World"。

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

1 个答案:

答案 0 :(得分: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}");
        }