智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也

C# 使用证书发起请求

private HttpClientHandler getHandler()
{
    string cacheKey = "handlerChche";
    HttpClientHandler handler = null; //cache.GetCache<HttpClientHandler>(cacheKey);
    if (handler == null)
    {
        handler = new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            SslProtocols = SslProtocols.Tls12
        };
        //获取证书路径
        //商户私钥证书,用于对请求报文进行签名
        handler.ClientCertificates.Add(new X509Certificate2(_ecrtpath, "123456", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet));
        //handler.ClientCertificates.Add(new X509Certificate2(CertHelper.GetDebugPath(), CertHelper.GetPwd(), X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet));
        handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
        handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
        
        //cache.SetCache(cacheKey, handler);
    }
    return handler;
}
 public static  string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
 {            
     postData = postData ?? "";
     using (HttpClient client = new HttpClient(getHandler()))
     {
         client.Timeout = new TimeSpan(0, 0, timeOut);
         if (headers != null)
         {
             foreach (var header in headers)
                 client.DefaultRequestHeaders.Add(header.Key, header.Value);
         }
         using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
         {
             if (contentType != null)
                 httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

             //HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
             //return response.Content.ReadAsStringAsync().Result;
             return client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
         }
     }
 }

 

posted @ 2024-02-23 10:59  後生哥哥  阅读(71)  评论(0编辑  收藏  举报
智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也