【问题标题】:How to handle Google Analytics Measurement Protocol http timeouts?如何处理 Google Analytics Measurement Protocol http 超时?
【发布时间】:2014-10-27 20:59:24
【问题描述】:

我正在通过 .NET C# (HttpWebRequest) 构建自己的 HTTP 请求,以将数据发布到谷歌分析测量协议。我已将 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());
}

【问题讨论】:

    标签: c# google-analytics httpwebrequest


    【解决方案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 分钟是您应该使用的最大值。如果您担心数据未发送,也可以考虑重试。

    【讨论】:

    • 你是怎么想出这 4 分钟的。我不确定 telnet 的具体时间。
    • man time - 运行程序并总结系统资源使用情况 man telnet - 用于与另一台主机进行交互通信
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2020-04-28
    • 1970-01-01
    • 2022-10-20
    相关资源
    最近更新 更多