如何处理Google Analytics测量协议http超时?

时间:2014-10-27 20:59:25

标签: c# google-analytics httpwebrequest

我通过.NET C#(HttpWebRequest)构建自己的HTTP请求,以将数据发布到Google Analytics分析测量协议。我已将http超时设置为30秒,这非常巨大。然而,我经常看到在我的环境和客户环境中发生超时。这不是一致的,这意味着它可能不是防火墙。

我不相信谷歌会定义使用什么超时。关于我可能做错什么或者我是否应该增加超时(30秒应该足够)的任何想法。

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" },
   { "tid", "UA-XXXXXXXX-X" },
   { "cid", userID.HasValue ? userID.Value.ToString() : "555"},
   { "t", type.ToString() },
   { "cd", screenName },
   { "cd1", "Custom 1"},
   { "cd2", "Custom 2"},
   { "cd3", "Custom 3 }
};

if (string.IsNullOrEmpty(postData["cd"]))
   postData.Remove("cd");

foreach (var keyValue in keyValues)
{
   postData.Add(keyValue.Key, keyValue.Value);
}

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);
request.Timeout = 30000;
// 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 ApplicationException("Google Analytics tracking did not return OK 200. Instead it returned " + webResponse.StatusCode.ToString());
   }
}
catch (Exception ex)
{
   logger.Error(ex.ToString());
}

1 个答案:

答案 0 :(得分:1)

Web浏览器通常有30秒超时。这可能是一个很好的起点。 这说1-2分钟:Browser Timeouts

$ time telnet google-analytics.com 80
Trying 173.194.79.103...
Connected to google-analytics.com.
Escape character is '^]'.
Connection closed by foreign host.

real    4m0.212s
user    0m0.012s
sys 0m0.012s

看起来4分钟是您应该使用的最大值。如果您担心未发送数据,也可以考虑重试。