使用 HTTPS 中的 WebRequest 访问 SSL 加密站点
尝试使用 WebRequest 从 HTTPS URL 检索内容时,开发人员可能会遇到错误,如果站点拥有无效的 SSL 证书。为了解决这个问题,必须采用适当的方法来处理 SSL 证书。
标准 WebRequest 方法包括:
Uri uri = new Uri(url); WebRequest webRequest = WebRequest.Create(uri); WebResponse webResponse = webRequest.GetResponse(); ReadFrom(webResponse.GetResponseStream());
但是,对于 SSL 加密的内容,还需要一个额外的步骤是必须的。通过在 Web 请求之前合并以下行:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
AcceptAllCertifications 回调定义为:
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }
程序可以有效忽略任何无效的 SSL 证书,从而使其能够成功访问HTTPS 内容。当使用用户提供的 URL(无法保证 SSL 证书的有效性)时,此方法特别有用。
以上是如何使用WebRequest访问SSL证书无效的HTTPS站点?的详细内容。更多信息请关注PHP中文网其他相关文章!