作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 C# 中创建一个方法,以从 url 返回网页 html 内容的字符串。我尝试了几种不同的方法,但出现错误 System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
以下在本地运行正常,但在远程服务器上运行时出现上述错误:
public static string WebPageRead(string url)
{
string result = String.Empty;
WebResponse response = null;
StreamReader reader = null;
try
{
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
return result;
}
最佳答案
这可能不是问题所在,但请尝试以下操作:
public static string WebPageRead(string url)
{
if (String.IsNullOrEmpty(url))
{
return null;
}
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
return null;
}
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader =
new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
我赞同之前的回答,建议您使用已知的良好 URL 进行尝试。我要补充一点,您应该使用已知良好的 HTTP 1.1 URL 进行尝试,注释掉将版本设置为 1.0 的行。如果这有效,那么它会大大缩小范围。
关于c# - 系统.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751056/
我是一名优秀的程序员,十分优秀!