网络请求错误?
编辑:已解决,问题出在服务器端。
我正在使用 C# 和 .NET2,我想知道这是一个 WebRequest bug。我用这个方法做了几个很好的请求,一切都很好,但之后每次我都会收到“操作已超时”。我实在不明白这是为什么。
public string RequestPage(string url) {
HttpWebRequest req = null;
string line = "";
string site = "";
try {
req = (HttpWebRequest) WebRequest.Create(url.Trim());
req.Timeout = 10000;
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
while ((line = reader.ReadLine()) != null) {
site += line;
}
return site;
} catch (Exception ex) {
MessageBox.Show("ERROR " + ex.Message);
}
return null;
}
EDIT: Solved, the problem was server-side.
I'm using C# and .NET2 and I wonder is that a WebRequest bug.. I do several good requests with this method and all is fine, but after that every time I get "The operation has timed out.". I really don't understand why is that.
public string RequestPage(string url) {
HttpWebRequest req = null;
string line = "";
string site = "";
try {
req = (HttpWebRequest) WebRequest.Create(url.Trim());
req.Timeout = 10000;
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
while ((line = reader.ReadLine()) != null) {
site += line;
}
return site;
} catch (Exception ex) {
MessageBox.Show("ERROR " + ex.Message);
}
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否解决了您的问题,但是完成后您应该始终处置 HttpWebResponse (以及实现 IDisposable 的其他对象):
如果您实际上不需要 HttpWebRequest 的所有功能,则可以使用 WebClient 改为:
I don't know if this solves your problem, but you should always dispose a HttpWebResponse (and other objects that implement IDisposable) when you're done:
If you don't actually require all the features of HttpWebRequest, you can use WebClient instead:
您不会处理响应:
基本上,您与之交谈的每个服务器都有池连接。因为您没有关闭响应,所以它们已经用完了。以上应该可以解决。
另外:
StringBuilder
在循环中连接文本内容。reader.ReadToEnd()
代替。You're not disposing of the response:
Basically there are pooled connections per server that you talk to. You're running out of them because you're not closing the response. The above should sort it out.
Additionally:
StringBuilder
to concatenate text content in a loop.reader.ReadToEnd()
instead.