我正在尝试在C#中创建一个方法,以便从网址返回一个网页html内容的字符串。我尝试了几种不同的方法,但是我收到错误 System.Net.WebException:底层连接已关闭:接收时发生意外错误。
以下在本地工作正常,但在远程服务器上运行时会出现上述错误:
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;
}
答案 0 :(得分:2)
这可能不是问题,但请尝试以下方法:
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的行。如果这样可行,那么它会大大缩小范围。
答案 1 :(得分:1)
感谢您的回复,问题是由于远程服务器上的DNS问题!为了确认,我最后使用了以下代码:
public static string WebPageRead(string url)
{
string content = String.Empty;
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
}
}
}
}
catch (Exception exc)
{
throw exc;
}
}
}
return content;
}
答案 2 :(得分:0)
之前有这样的问题是通过在问题机器上的IE中打开网址来解决的。然后,IE会询问您是否要将URL添加到安全站点列表中。添加它,它适用于该URL。
这只是可能的原因之一。严重的是,很多其他问题都可能导致这种情况。除了上面描述的问题,我发现解决这个问题的最好方法是捕获异常并重试请求。