解决https 请求过程中SSL问题

Posted jianliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决https 请求过程中SSL问题相关的知识,希望对你有一定的参考价值。

最近一个项目中用到了https的请求,在实际调用过程中发现之前的http方法不支持https,调用一直报错。

查询了一下,添加几行代码解决问题。

 public string HttpPost(string Url, string postDataStr, string useragent = null)
       
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;//新增一行
            System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;//新增第二行,很重要
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//新增第三行
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            if (!string.IsNullOrEmpty(useragent))
           
                request.UserAgent = useragent;
           
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();


            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
       

以上是关于解决https 请求过程中SSL问题的主要内容,如果未能解决你的问题,请参考以下文章

Android 4.x HTTPS请求SSL handshake aborted异常解决

C# https证书通信Post/Get(解决做ssl通道时遇到“请求被中止: 未能创建 SSL/TLS 安全通道”问题)

JDK版本不同引发的https请求证书问题

如何在 .Net C# 中绕过 SSL 证书进行 HTTPS SOAP 请求?

VSCode 输出 java SSL 请求过程

[HTTPS] - 请求API失败(Could not create SSL/TLS secure channel)之解决