C# get 网址时出现异常“The underlying connection was closed: An unexpected error occurred on a send”
static void Main(string[] args)
{
try
{
string str = GetData("https://www.abc.com");
}
catch (WebException ex)
{
}
}
public static string GetData(string url)
{
try
{
string result = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "Get";
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
httpWebResponse.Close();
httpWebRequest.Abort();
return result;
}
catch
{
throw;
}
}
当前为.net 2.0控制台应用程序,后来发现原因是安全传输协议升级到TLS1.2了,于是添加下面的代码,问题解决。
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
string str = GetData("https://www.abc.com");
}
catch (WebException ex)
{
}
}
注意 .net 版本建议切换为4.5以上。