【问题标题】:webClient - servicepointmanager freeze my project - C#webClient - servicepointmanager 冻结我的项目 - C#
【发布时间】:2020-10-27 07:02:47
【问题描述】:

我使用“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);
}

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

【问题讨论】:

    标签: c# webclient servicepointmanager


    【解决方案1】:

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

    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);
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多