【发布时间】: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