赞
踩
HTTPS协议请求需要设置安全协议,代码如下
public static string Post(string url, string param) { string result = ""; System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); req.ProtocolVersion = System.Net.HttpVersion.Version11; // 这里设置了协议类型。 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; // SecurityProtocolType.Tls1.2; req.KeepAlive = false; System.Net.ServicePointManager.CheckCertificateRevocationList = true; System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.Net.ServicePointManager.Expect100Continue = false; } req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Referer = null; req.AllowAutoRedirect = true; req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; req.Accept = "*/*"; byte[] data = System.Text.Encoding.UTF8.GetBytes(param); // 把字符串转换为字节 req.ContentLength = data.Length; //请求长度 using (System.IO.Stream reqStream = req.GetRequestStream()) // 获取 { reqStream.Write(data, 0, data.Length);// 向当前流中写入字节 reqStream.Close(); // 关闭当前流 } System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse(); //响应结果 System.IO.Stream stream = resp.GetResponseStream(); //获取响应内容 using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; } private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) { return true; // 总是接受 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。