0

我使用“ServicePointManager”来解决“请求被中止:无法创建 SSL/TLS 安全通道”的问题。

try
{
   // ServicePointManager.Expect100Continue = true;
   // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
   //
   // or this
   //
   // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
   
   var client = new WebClient();
   var str = client.DownloadString(url);
   textBox1.Text = str;
}catch (Exception ex){
   MessageBox.Show(ex.Message);
}

但我的项目冻结/挂起。有人能帮我吗?

4

1 回答 1

0

尝试使用异步。这对我来说很好。

using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.Multiline = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var html = await client.DownloadStringTaskAsync(new Uri("https://www.google.com"));
                    textBox1.Text = html;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
于 2020-07-07T04:43:13.077 回答