Requesting html over https with c# Webclient

后端 未结 4 755
忘掉有多难
忘掉有多难 2020-11-29 07:23

I am attempting various html resources via c# WebClient class from a site I have no control over. When I attempt to access urls such as \"https://archive.org/details/OTRR_

相关标签:
4条回答
  • 2020-11-29 08:06

    I tried this example and received the error "The request was aborted: Could not create SSL/TLS secure channel"

    To fix this problem it's possible to change the SecurityProtocol in my case Tls12 and it's working good.

    0 讨论(0)
  • 2020-11-29 08:18

    Have a read of this: http://support.microsoft.com/kb/915599

    The server you are accessing doesn't support TLS so you will need to force it to use SSL3.

    Add the following line to your call:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    

    Here's a fully working example:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    
    class Program
    {
        static void Main(string[] args)
        {
            Uri address = new Uri("https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles");
    
            ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ;
    
            using (WebClient webClient = new WebClient())
            {
                var stream = webClient.OpenRead(address);
                using (StreamReader sr =new StreamReader(stream))
                {
                    var page = sr.ReadToEnd();
                }
            }
        }
    
        /// <summary>
        /// Certificate validation callback.
        /// </summary>
        private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (error == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }
    
            Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
                cert.Subject,
                error.ToString());
    
            return false;
        }
    
    0 讨论(0)
  • 2020-11-29 08:27

    Just add this line before var stream = webClient.OpenRead(address);

    System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; };
    

    That should sort out the SSL/TLS error

    0 讨论(0)
  • 2020-11-29 08:29

    in .net Framework 4.0 add

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2
    
    0 讨论(0)
提交回复
热议问题