HttpWebRequest超时

3
我已经阅读了以下两篇文章,并尝试实现相同的内容。
我的代码是这样的,超时发生在这里。
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

我读过的文章:

这里

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

任何线索都会有所帮助。有时我可以成功发送一个请求,但所有其他请求都失败了,或者全部失败。我正在向一个HTTPS网站发布信息。使用Fiddler运行时没有问题。
更新1: 我尝试了zbugs的建议,但结果是相同的问题。第一个请求通过了,后续的请求都失败了。我关闭了所有响应流,并在我的请求对象上调用了abort方法。
3个回答

5

我需要这样做吗? wr.ServicePoint.ConnectionLeaseTimeout = 5000; wr.ServicePoint.MaxIdleTime = 5000; ServicePointManager.MaxServicePointIdleTime = 5000; Stream rs = wr.GetRequestStream();因为这导致了相同的超时异常。 - user721264
不要忘记设置 ServicePointManager.MaxServicePointIdleTime 等参数,完成后必须释放 wr 对象和流。 - zbugs
是的,我有Close和Dispose方法,还有wr.Abort()。 - user721264
在进入该方法或创建wr对象之前,您需要尝试一下。设置ServicePointManager值。 - zbugs

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()))
    {
    ...
    }
}

0

在我的一个请求调用中,我没有成功调用

Request.Abort()

这似乎解决了我的问题,还有来自zbugs的建议


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接