如何使用WebRequest的访问加密使用HTTPS站点的SSL?
-
05-09-2019 - |
题
我正在写一个程序,它从用户提供的URL内容中读取。我的问题是在是这样的代码:
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
和如果所提供的,这是破 URL 的是一个 “HTTPS://” 的网址。谁能帮我更改此代码,以便将与SSL加密的内容合作。感谢。
解决方案
您正在做正确的方式,但用户可提供的网址已安装无效的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;
}
其他提示
这个链接将是你的兴趣: http://msdn.microsoft的.com / EN-US /库/ ds8bxk2a.aspx
有关HTTP连接,所述的WebRequest和WebResponse类使用SSL与支持SSL网络主机进行通信。使用SSL的决定是由WebRequest类制造的基础上,它被赋予的URI。如果URI以“https:”,使用SSL;如果URI开始以“http:”,未加密的连接用于
对于我来说这一个工作:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
不隶属于 StackOverflow