【发布时间】:2021-12-25 19:33:05
【问题描述】:
因为这是很常见的问题,但没有合适的解决方案可以解决我的问题。
我在尝试从 StreamReader 读取/加载数据时遇到此问题
这是我的代码。
public bool WebSiteIsAvailable(HttpWebRequest request, HttpWebResponse response)
{
request.Timeout = 15000;
request.Method = "HEAD"; // As per Lasse's comment
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException)
{
return false;
}
}
public string ParseHtml(string html)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(html);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1251));
if (WebSiteIsAvailable(request, response))
{
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
response.Close(); // While using WebResponse please make sure that you close the response stream ie(.close) else it would hang the machine after certain repeated execution.Eg
}
else
{
response.Close();
}
return html;
}
【问题讨论】:
-
您是在维护代码还是编写新代码?如果是新代码,请考虑使用
System.Net.Httphere。您还连续两次致电GetResponse,这是想要的行为吗?
标签: c# .net visual-studio winforms web-crawler