2014-10-27 83 views
0

我正在通過.NET C#(HttpWebRequest)構建自己的HTTP請求,以便將數據發佈到Google分析測量協議。我已將http超時設置爲30秒,這非常大。然而,我經常看到在我的環境和客戶環境中發生超時。這是不一致的,這意味着它可能不是防火牆的事情。如何處理Google Analytics測量協議http超時?

我不相信谷歌定義了什麼超時使用。任何關於我可能做錯的想法,或者如果我應該增加超時時間(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

網頁瀏覽器通常會有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 

貌似四分鐘一到,你應該使用最大。如果您擔心數據未發送,您也可以考慮重試。

+0

你是怎麼想出4分鐘的。我不確定telnet是什麼時間。 – Mark 2014-10-29 17:06:19

+0

man time-run程序並彙總系統資源使用情況 man telnet - 用於與另一臺主機進行交互式通信 – 2014-11-05 23:02:48