HTTPS請求筆記- SSL安全通道驗證問題

郎中令發表於2024-07-19

一直以來,遇到的POST介面請求都是 鍵值對的json格式,最近對接了不少公安,發現body 的請求體都是直接放置字串,雖然postman 中會報紅,但是仍然可請求成功

            using (HttpClientHandler handle = new HttpClientHandler())
            using (HttpClient httpClient = new HttpClient(handle))
            {
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);
                string appKey = "xxxx";
                //構造簽名相關
                string timeStamp = "";
                string sign = GetSign(ref timeStamp, appKey);
                httpRequestMessage.Headers.Add("sign", sign);
                httpRequestMessage.Headers.Add("引數1", timeStamp);
                httpRequestMessage.Headers.Add("引數2", "xxxx");

                //var requestData = new { sign = args };  取消鍵值對,直接放body值 
                StringContent content = new StringContent(args, Encoding.UTF8, "application/json");
                httpRequestMessage.Content = content;
                var httpResponseMessage = httpClient.SendAsync(httpRequestMessage);
                string result = httpResponseMessage.Result.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<dynamic>(result);
            }

在透過 https 請求時,有時候會遇到過安全驗證問題,比如什麼SSL, TLS啥的, 不得不說AI確實方便,一鍵輸入,直接對話出結果,雖然時常不怎麼靠譜,但是也提供了很多好思路,很適合比較社交恐懼的馬龍, 需要設定一下證書回撥,安全協議

           
            if (url.StartsWith("https"))
            {
//設定證書,設定安全協議 ServicePointManager.SecurityProtocol
= SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; } using (HttpClientHandler handle = new HttpClientHandler()) using (HttpClient httpClient = new HttpClient(handle)) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url); string appKey = "xxxx"; //構造簽名相關 string timeStamp = ""; string sign = GetSign(ref timeStamp, appKey); httpRequestMessage.Headers.Add("sign", sign); httpRequestMessage.Headers.Add("引數1", timeStamp); httpRequestMessage.Headers.Add("引數2", "xxxx"); //var requestData = new { sign = args }; 取消鍵值對,直接放body值 StringContent content = new StringContent(args, Encoding.UTF8, "application/json"); httpRequestMessage.Content = content; var httpResponseMessage = httpClient.SendAsync(httpRequestMessage); string result = httpResponseMessage.Result.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<dynamic>(result); }

回撥方法的實現

        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

相關文章