首页 > dotnet, web, 技术, 灌水 > C# WebRequest处理Https请求

C# WebRequest处理Https请求

2009年9月29日 7,866 人浏览 发表评论 阅读评论

正常情况下,处理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:

  1. C# WebRequest处理Https请求之使用客户端证书
  2. C# WebRequest发起Http Post请求模拟登陆并cookie处理示例
分类: dotnet, web, 技术, 灌水 标签: , ,
1 Star2 Stars3 Stars4 Stars5 Stars 来给这篇文章评分吧!
Loading ... Loading ...
  1. 2010年3月26日01:48 | #1

    无意间进来了,博客很nice,很漂亮

  2. peter
    2011年10月12日17:04 | #2

    thank for your message

  3. 2012年4月24日16:02 | #3

    谢谢。还是你解释的清楚。

  1. 2012年4月24日15:49 | #1