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

    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; //总是接受
    }

  • 相关阅读:
    Leetcode 238. Product of Array Except Self
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 290. Word Pattern
    Leetcode 205. Isomorphic Strings
    Leetcode 107. Binary Tree Level Order Traversal II
    Leetcode 102. Binary Tree Level Order Traversal
    三目运算符
    简单判断案例— 分支结构的应用
    用switch判断月份的练习
    java基本打印练习《我行我素购物系统》
  • 原文地址:https://www.cnblogs.com/jingzhishen/p/3504843.html
Copyright © 2011-2022 走看看