zoukankan      html  css  js  c++  java
  • C# WebRequest处理Https请求

    正常情况下,处理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处理示例
  • 相关阅读:
    Hua Dan stories | Hua Dan
    字典树(前缀树)的应用 乖兔子的专栏 博客频道 CSDN.NET
    《算法精解:C语言描述》勘误
    curl
    javascript实现的gzip压缩(deflate)和解压缩(inflate)算法 sudone.com服务器系统架构分析日志
    python处理gzip压缩的http数据 XII 博客大巴
    Zlib与GZip woaidongmao C++博客
    文件压缩/解压算法 cutepig 博客园
    url
    转:Ubuntu Terminal 使用和常用快捷键
  • 原文地址:https://www.cnblogs.com/youlechang123/p/2976630.html
Copyright © 2011-2022 走看看