gpt4 book ai didi

c# - 系统.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive

转载 作者:行者123 更新时间:2023-11-30 22:50:06 33 4
gpt4 key购买 nike

我正在尝试在 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com