我正在尝试从 WPF 应用程序向 Google Analytics 发送数据。我在网上找不到任何明确定义如何执行此操作的资源。我知道有许多可用的 NuGet 包,但我不确定使用哪个,也不知道如何实现它们。我也知道有一些第三方“帮助”库可用(参见 Using Google Analytics from a .NET desktop application ),我对此不感兴趣。看起来大多数在线说明都在展示如何从 GA 中“提取”数据,而不是如何推。不是寻找“也许”或变通方法,而是寻找通常最直接的方法。这应该不复杂。只需要一个“Hello World”。
你能给我指明正确的方向吗?谢谢,
最佳答案
这对我有用:
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}");
}
关于wpf - 从 WPF 向 Google Analytics 提交数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352794/