Programmatically Access SSL Encrypted Content Via HTTPS with WebRequest
When interacting with URLs via WebRequest, encountering difficulties due to SSL encryption is not uncommon. This article aims to provide a solution to overcome such challenges.
The code snippet you provided attempts to retrieve content from a URL but encounters an error when the URL uses the HTTPS protocol. To handle this situation, it's essential to adjust your code to accommodate SSL encrypted content.
The key solution lies in introducing ServicePointManager.ServerCertificateValidationCallback, a delegate that allows you to handle SSL certificate validation. By overriding its default behavior, you can instruct the code to accept all certifications, including those that may be invalid.
To achieve this, add the following line before making the web request:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Then, create a simple method called AcceptAllCertifications to return true:
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }
With these modifications, your code will be able to access and read content from URLs that use HTTPS encryption, regardless of the certificate validity.
The above is the detailed content of How to Programmatically Access HTTPS Content Using WebRequest Despite SSL Errors?. For more information, please follow other related articles on the PHP Chinese website!