C# HTTPS請求“請求被中止: 未能創(chuàng)建 SSL/TLS 安全通道”
當前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
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); //轉(zhuǎn)換為bytes數(shù)據(jù) // 準備請求... try { // 設(shè)置參數(shù) if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必須加上這一句,根據(jù)需要更改值 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(); //發(fā)送請求并獲取相應回應數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網(wǎng)頁發(fā)送Post請求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回結(jié)果網(wǎng)頁(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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |