我正在写一个程序,它从用户提供的URL读取内容。我的问题是在是这样的代码:
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
这也是打破,如果提供的URL是“https://开头的” URL。谁能帮我更改此代码,以便将与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/library/ds8bxk2a.aspx
对于HTTP连接,WebRequest类和WebResponse类使用SSL与支持SSL的Web主机进行通信。使用SSL的决定是由WebRequest类制造的基础上,它被赋予的URI。如果URI以“https:”,使用SSL;如果URI开始以“http:”时,使用未加密的连接。
这一次为我工作:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;