C# GET https 网址“The underlying connection was closed: An unexpected error occurred on a send”错误

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以上。


作者最新文章
C# 删除一维数组内的某个值(元素), C# 删除数组元素的方法
C# 如何判断一个字符串是否包含另一个字符串的方法,C# IndexOf 的使用
Winform 只能输入整数的TextBox (文本框) 控件
Winform 禁止重复启动,单实例exe程序
Winform TextBox (文本框) 控件禁止输入内容