.net core上传“https”的post接口

如果采用之前的HttpWebRequest方法是实现https的请求,会报错无法建立SSL连接
换一种读取方式 参考地址

1 ,https://blog.csdn.net/shanghaibao123/article/details/124116749
2,https://www.bbsmax.com/A/amd00jxjdg/
3,https://www.cnblogs.com/bjxxlbm/articles/14644030.html

1 首先在NuGet中下载包

Microsoft.Extensions.Http

2 在启动类ConfigureServices中配置启用https

  //.net  core添加https 正式配置
            services.AddHttpClient(Options.DefaultName, c =>
            {
                // ...
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                    ServerCertificateCustomValidationCallback =
                        (httpRequestMessage, cert, certChain, policyErrors) => true
                };
            });

3 调用

先在Service中构造函数中注入

      private readonly IHttpClientFactory _httpClientFactory;
        public TCQXXCLService( IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

调用

       /// <summary>
        /// 获取https  不传参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public string GetApi(string url, string json)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient();
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/plain");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
   
                var httpResponseMessage = httpClient.GetAsync(url);

                //  var httpResponseMessage = httpClient.GetAsync(url);
                var content = httpResponseMessage.Result.ToString();
                return content;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        /// <summary>
        /// post传参数 json格式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestJson"></param>
        /// <returns></returns>
        public string HttpClientPost(string url, string requestJson)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Uri postUrl = new Uri(url);
            var encodeBytes = Encoding.UTF8.GetBytes(requestJson);
            using (HttpContent httpContent = new ByteArrayContent(encodeBytes))
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var client1 = _httpClientFactory.CreateClient();
                client1.Timeout = new TimeSpan(0, 0, 60);
                var result = client1.PostAsync(postUrl, httpContent).Result.Content.ReadAsStringAsync().Result;
                return result;

            }
        }



        /// <summary>
        /// post传参数 json格式  Authorization  Bearer
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestJson"></param>
        /// <returns></returns>
        public string PostBearerAsync(string url, string token, string requestJson)
        {
            string content = "";
            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Uri postUrl = new Uri(url);
                var encodeBytes = Encoding.UTF8.GetBytes(requestJson);
                using (HttpContent httpContent = new ByteArrayContent(encodeBytes))
                {
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var client1 = _httpClientFactory.CreateClient();
                    client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                    client1.Timeout = new TimeSpan(0, 0, 60);
                    content = client1.PostAsync(postUrl, httpContent).Result.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.LogInformation("post https请求失败" + ex.Message);
            }
            return content;
        }



        /// <summary>
        /// post传参数 json格式 Basic 认证
        /// </summary> 
        /// <param name="url"></param>
        /// <param name="requestJson"></param>
        /// <returns></returns>
        public string PostbasicAsync(string url, string requestJson, string m_Username, string m_Password)
        {
            string content = "";
            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Uri postUrl = new Uri(url);
                var encodeBytes = Encoding.UTF8.GetBytes(requestJson);
                using (HttpContent httpContent = new ByteArrayContent(encodeBytes))
                {
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var client1 = _httpClientFactory.CreateClient();
                    string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
                    byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
                    string base64Credentials = Convert.ToBase64String(byteCredentials);

                    client1.DefaultRequestHeaders.Add("Authorization", "Basic " + base64Credentials);
                    client1.Timeout = new TimeSpan(0, 0, 60);
                    content = client1.PostAsync(postUrl, httpContent).Result.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.LogInformation("post https请求失败" + ex.Message);
            }
            return content;
        }

如果上面get方法不通 使用以下方法

       public string Get(string url)
        {

            //从工厂获取请求对象
            var client = _httpClientFactory.CreateClient();
            //   client.DefaultRequestHeaders.Add("Content-Type", "application/json");
            //拼接地址
            client.BaseAddress = new Uri(url);
            return client.GetStringAsync(url).Result;

        }
posted @   原往  阅读(265)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2021-08-31 git命令
2021-08-31 git介绍
2021-08-31 git安装
点击右上角即可分享
微信分享提示