如何以编程方式在Google Analytics中插入数据

时间:2015-02-27 05:18:14

标签: google-analytics google-analytics-v4 google-analytics-sdk

您能否告诉我以下代码以编程方式在Google Analytics中插入网页视图有什么问题。

代码未插入网页浏览。

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

            // the request body we want to send
            var postData = new Dictionary<string, string>
{
{ "v", "1" },
{ "tid", "UA-XXXXXX-1" },
{ "cid", "555" },
{ "t", "pageview" },
{"dh","www.pomroofing.com"},
{ "dp", "/phone/123/456/789/1" },
{ "dt", "homepage" },
};


            var postDataString = postData
            .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
            HttpUtility.UrlEncode(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);
            }

            try
            {
                var webResponse = (HttpWebResponse)request.GetResponse();
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpException((int)webResponse.StatusCode,
                    "Google Analytics tracking did not return OK 200");
                }
            }
            catch (Exception ex)
            {
                // do what you like here, we log to Elmah
                // ElmahLog.LogError(ex, "Google Analytics tracking failed");
            }

请帮助,或者是否有任何api。

1 个答案:

答案 0 :(得分:2)

尝试将完整的请求字符串直接测试到浏览器中。像这样的简短请求也可以通过GET发送。

检查实时报告,看看它是否显示。 (我测试了这个)

http://www.google-analytics.com/collect?v=1&tid=UA-XXXX-X&cid=555&t=pageview&dh=www.pomroofing.com&dp=/phone/123/456/789/1&dt=homepage

这没有API。

BTW你遗失/收集的网址:)