HttpWebRequest超时

时间:2012-05-18 20:30:34

标签: c# timeout httpwebrequest

我已阅读以下2篇文章,并尝试实施相同的内容。

我的代码是这样,超时发生在这里

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.CookieContainer = cookieJar;

wr.Proxy = null;
wr.ServicePoint.ConnectionLeaseTimeout = 5000;
Stream rs = wr.GetRequestStream(); // -> Time out error occurs here

Article I read

My code using that as a sample
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.CookieContainer = cookieJar;

wr.Timeout = 5000;
wr.Proxy = null;

wr.ServicePoint.ConnectionLeaseTimeout = 5000;
wr.ServicePoint.MaxIdleTime = 5000;

Stream rs = wr.GetRequestStream(); //-->Time out error

任何线索都会有所帮助。有时我可以通过1请求,所有其他请求都失败或一切都失败。我发布到HTTPS站点。使用Fiddler

运行时没有问题

更新1: 我试着遵循zbugs的想法,但这导致了同样的问题。第一个请求通过后续的请求失败。我正在关闭所有响应流以及在我的请求对象上调用abort。

3 个答案:

答案 0 :(得分:4)

你需要设置它。

const int maxIdleTimeout = 5000;
ServicePointManager.MaxServicePointIdleTime = maxIdleTimeout;

如果您在任何给定时间有多个客户提出请求,

const int maxConnections = 100; //or more/less
ServicePointManager.DefaultConnectionLimit = maxConnections;

http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.maxservicepointidletime.aspx

答案 1 :(得分:1)

您应该释放实施IDisposable的所有资源。不释放它们会导致您正在尝试的问题。

这里有一个例子,不是你的代码,但它会帮助你理解我的意思

var request = WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";

using (var response = request.GetResponse())
{
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
    ...
    }
}

答案 2 :(得分:0)

在我的一个请求电话中,我没有打电话

Request.Abort()

这似乎解决了我的问题以及来自zbugs的建议