Home >Backend Development >C++ >How to Access HTTPS Sites with Invalid SSL Certificates Using WebRequest?
Accessing SSL Encrypted Sites with WebRequest in HTTPS
When attempting to retrieve content from an HTTPS URL using WebRequest, developers may encounter errors if the site possesses an invalid SSL certificate. To address this issue, it is essential to employ the appropriate methods for handling SSL certificates.
The standard WebRequest approach involves:
Uri uri = new Uri(url); WebRequest webRequest = WebRequest.Create(uri); WebResponse webResponse = webRequest.GetResponse(); ReadFrom(webResponse.GetResponseStream());
However, for SSL-encrypted content, an additional step is required. By incorporating the following line before the web request:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
With the AcceptAllCertifications callback defined as:
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }
The program can effectively ignore any invalid SSL certificates, allowing it to successfully access HTTPS content. This approach is particularly useful when working with user-provided URLs, where the validity of SSL certificates cannot be guaranteed.
The above is the detailed content of How to Access HTTPS Sites with Invalid SSL Certificates Using WebRequest?. For more information, please follow other related articles on the PHP Chinese website!