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# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角
C# Word 转换 PDF 文件,如何转换 PDF