如何使用WebRequest使用https访问SSLencryption站点?

我正在写一个程序,从用户提供的URL中读取内容。 我的问题是在这样的代码:

Uri uri = new Uri(url); WebRequest webRequest = WebRequest.Create(uri); WebResponse webResponse = webRequest.GetResponse(); ReadFrom(webResponse.GetResponseStream()); 

如果提供的url是“https://”url,则会中断。 任何人都可以帮助我更改此代码,以便它可以使用SSLencryption的内容。 谢谢。

您正在以正确的方式进行操作,但用户可能会向安装了无效ssl证书的网站提供url。 如果您在进行实际的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/library/ds8bxk2a.aspx

对于http连接,WebRequest和WebResponse类使用SSL与支持SSL的Web主机进行通信。 使用SSL的决定是由WebRequest类根据给定的URI来完成的。 如果URI以“https:”开头,则使用SSL; 如果URI以“http:”开头,则使用未encryption的连接。

这个为我工作:

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;