zoukankan      html  css  js  c++  java
  • .Net Core 发送https请求/.net core 调用数字证书 使用X509Certificate2

    .Net Core 发送https请求

    .net core 调用数字证书 使用X509Certificate2

    .NET下面的 .netfromwork使用和asp.net core下使用方式不一样

    .Net Core中的使用方式代码:

            /// <summary>
            /// 指定Post地址使用Get 方式获取全部字符串
            /// </summary>
            /// <param name="url">请求后台地址</param>
            /// <param name="content">Post提交数据内容(utf-8编码的)</param>
            /// <returns></returns>
            public static string PostSsl3(string url, string content)
            {
                string path = @"D:SiteQL.Back.APIwwwrootfilecertapiclient_cert.p12";
                string password = "xxxx";
    
                //HttpClient请求,在handler里添加X509Certificate2 证书,数据data是byte[] 类型,所以需要使用ByteArrayContent传入
                var handler = new HttpClientHandler();
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.SslProtocols = SslProtocols.Tls12;
                //获取证书路径
                //商户私钥证书,用于对请求报文进行签名
                handler.ClientCertificates.Add(new X509Certificate2(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet));
                handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
                handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                //post请求
                var client = new HttpClient(handler);
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(content);
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置,否则发送无效
                    HttpContent hc = new StreamContent(ms);
                    var response = client.PostAsync(url, hc).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }

    更多:

    .Net Standard HttpClient封装Htt请求常用操作整理

    .Net Standard Http请求实例

    .Net Standard 类库的创建和使用

  • 相关阅读:
    第二十二章 CLR寄宿和AppDomain
    第二十一章 托管堆和垃圾回收
    第二十章 异常和状态管理
    第十九章 可空值类型
    第十八章 定制特性
    第十七章 委托
    第十六章 数组
    第十五章 枚举类型和位标志
    html标签溢出问题
    Java 路径问题
  • 原文地址:https://www.cnblogs.com/tianma3798/p/11321981.html
Copyright © 2011-2022 走看看