美文网首页
c# HttpWebRequest https 提示基础连接已经

c# HttpWebRequest https 提示基础连接已经

作者: 华子的笔记本 | 来源:发表于2019-05-06 12:50 被阅读0次

    在工作中要获取一个网络api下的内容,因为要auth认证,本以为很简单

    string url="https://.....";
    string usernamePassword = CustomerID + ":" + CustomerCertificate;
    string basic = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
    myReq.Headers.Add("Authorization", "Basic " + basic);
    HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();  //<-- 这里就报错了
    Stream resStream = myRes.GetResponseStream();
    StreamReader strReader = new StreamReader(resStream);
    string resStr = strReader.ReadToEnd();
    Console.WriteLine(resStr);
    

    结果运行时提示“提示基础连接已经关闭: 发送时发生错误。”
    在浏览器下访问网址则正常,刚开始怀疑是basic不对,在浏览器下用同样的值模拟了一下能正常获取,然后把https换成http程序又能正常获取了,定位到问题出在ssl证书上
    查了一下资料
    添加以下代码

    ServicePointManager.Expect100Continue = true;
    ServicePointManager.CheckCertificateRevocationList = true;
    ServicePointManager.DefaultConnectionLimit = 100;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; 
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    

    改回https还是提示原来的异常,换了另外一个https的网址测试却又正常,在浏览器下对比两个https网址的ssl证书,发现能正常访问的测试网址是tls1.0 不能访问的网址是tls1.2
    找到问题了,原来在.net4.5以下tls1.2的设置如下

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; 
    //.net4.5及以上
    //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    再次运行,ok

    相关文章

      网友评论

          本文标题:c# HttpWebRequest https 提示基础连接已经

          本文链接:https://www.haomeiwen.com/subject/wrsroqtx.html