HTTPS请求笔记- SSL安全通道验证问题

一直以来,遇到的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;
        }

 

posted @ 2024-07-19 15:28  郎中令  阅读(1)  评论(0编辑  收藏  举报