http://www.cnblogs.com/youlechang123/archive/2013/03/23/2976630.html
正常情况下,处理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; //总是接受
}