前几日对接别的平台时,发送的请求是https,发送请求时会遇到“基础连接已经关闭: 发送时发生错误”的问题。看到了平台上的问题解答,发现这个方法挺好用,就在此记录一下。

/// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string Post(string url, string paramString)
        {
            string result = "";
            //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebRequest request = null;
            //如果是发送HTTPS请求 
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //关于ServicePointManager.SecurityProtocol的设置是解决问题的关键。
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
                //.Net4.0
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                //.Net4.5
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls1.2;
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;

            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Timeout = 5000;
            request.Method = "POST";
            request.ContentType = "application/json";
            #region 添加Post 参数

            byte[] data = Encoding.UTF8.GetBytes(paramString);
            request.ContentLength = data.Length;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受 
        }