C# HTTPS请求“请求被中止: 未能创建 SSL/TLS 安全通道”
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"; private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } public static string HttpsPost(string url, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.GetEncoding("utf-8"); //选择编码字符集 byte[] data = encoding.GetBytes(postData); //转换为bytes数据 // 准备请求... try { // 设置参数 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必须加上这一句,根据需要更改值 request = WebRequest.create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.create(url) as HttpWebRequest; } CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Timeout = 30*1000; //30S request.ContinueTimeout = 30 * 1000; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = data.Length; request.UserAgent = DefaultUserAgent; // request.TransferEncoding = encoding.HeaderName; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return string.Empty; } } 该文章在 2023/5/23 9:52:52 编辑过 |
关键字查询
相关文章
正在查询... |