using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; namespace SAL_OUTSTOCK.Utils { public static class HttpWebHelper { /// /// post请求 /// /// 请求地址 /// 请求数据 /// 证书 /// public static string DoPost(string url, string postData, X509Certificate2 certificate2) { try { string result = string.Empty; HttpWebRequest request = null; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } else { request = (HttpWebRequest)WebRequest.Create(url); } //string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; ////证书 //var keystorefile = baseDirectory + @"\bin\ISSUE\testISSUE.pfx"; //var key = "123456"; //var cer = new X509Certificate2(keystorefile, key); if (certificate2 != null) request.ClientCertificates.Add(certificate2); request.Method = "POST"; //使用get方式发送数据 request.ContentType = "application/json;charset=utf-8"; byte[] data = Encoding.UTF8.GetBytes(postData); Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; } catch (Exception ex) { throw ex; } } /// /// post请求 /// /// /// /// public static string DoPost(string url, string postData) { return DoPost(url, postData, null); } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { if (errors == SslPolicyErrors.None) return true; //总是接受 return false; } } }