正常情况下,处理https和http没有什么区别,如以下代码,显示了https://www.softlayer.com/的内容
string url = “https://www.softlayer.com/”; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); Console.Write(reader.ReadToEnd()); response.Close();
和http的不同就是地址由http改为了https
但是,如果你将 https://www.softlayer.com/ 改为 https://softlayer.com/,会发现一个异常 未能为 SSL/TLS 安全通道建立信任关系 怎么回事? 用浏览器试一下,访问 https://www.softlayer.com/ 没有问题 访问 https://softlayer.com/ 会有证书问题(虽然是我们自己造成的) 这就对了,如果有证书问题,不做特殊处理,将会抛出异常 怎么处理呢? 如果是dot net 2.0 或以上,加上一个确认函数就可以了,代码如:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); string url = “https://softlayer.com/”; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); Console.Write(reader.ReadToEnd()); response.Close();
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Always accept Console.WriteLine(“accept ” + certificate.GetName()); return true; //总是接受 }
using System.Net; using System.IO; using System.Web; using System.Net.Security; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates;
如果是dot net 1.1,写法略有不同
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
internal class AcceptAllCertificatePolicy : ICertificatePolicy { public AcceptAllCertificatePolicy() { } public bool CheckValidationResult(ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest wRequest, int certProb) { // Always accept return true; } }
Related posts:
- C# WebRequest处理Https请求之使用客户端证书
-
C# WebRequest发起Http Post请求模拟登陆并cookie处理示例
|
请发表评论