首页 > 编程语言 >C# HttpClient 封装

C# HttpClient 封装

时间:2022-11-03 14:12:01浏览次数:49  
标签:封装 string header C# headers url new null HttpClient

using System.Text;

namespace HTTPClientPacking
{
    public class HttpClientHelper
    {
        private static HttpClientHelper? _httpClientHelper = null;

        private HttpClient? _httpClient;

        private static object _lock = new object();

        private HttpClientHelper()
        {
        }

        public static HttpClientHelper GetInstance()
        {
            lock (_lock)
            {
                if (_httpClientHelper is not null) return _httpClientHelper;

                //取消使用默认的Cookies和证书验证
                HttpClientHandler handler = new()
                {
                    UseCookies = false,
                    ServerCertificateCustomValidationCallback = (t1, t2, t3, t4) => true
                };
                return _httpClientHelper = new HttpClientHelper() { _httpClient = new HttpClient(handler) };
            }
        }

        public string? Get(string url, IDictionary<string, string>? headers = default)
        {
            if (url is null) throw new ArgumentNullException(nameof(url));

            using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            if (headers is not null)
            {
                foreach (var header in headers!)
                {
                    request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            var res = _httpClient?.SendAsync(request).Result.Content.ReadAsStringAsync().Result;

            return res;
        }

        public async Task<string?> GetAsync(string url, IDictionary<string, string>? headers = default)
        {
            if (url is null) throw new ArgumentNullException(nameof(url));

            using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            if (headers is not null && headers.Count > 0)
            {
                foreach (var header in headers!)
                {
                    request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            var res = _httpClient?.SendAsync(request).Result.Content.ReadAsStringAsync();

            return await res!;
        }

        public string? Post(string url, string? paramData = null, IDictionary<string, string>? headers = null)
        {
            StringContent stringContent = new StringContent(paramData ?? string.Empty, Encoding.UTF8);

            if (headers is not null && headers.Count > 0)
            {
                foreach (var header in headers!)
                {
                    stringContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            stringContent.Headers.Add("ContentType", "application/json");

            return _httpClient?.PostAsync(new Uri(url), stringContent).Result.Content.ReadAsStringAsync().Result;
        }

        public async Task<string?> PostAsnc(string url, string? paramData = null, IDictionary<string, string>? headers = null)
        {
            StringContent stringContent = new StringContent(paramData ?? string.Empty, Encoding.UTF8);

            if (headers is not null && headers.Count > 0)
            {
                foreach (var header in headers!)
                {
                    stringContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            stringContent.Headers.Add("ContentType", "application/json");

            return await _httpClient!.PostAsync(new Uri(url), stringContent).Result.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 设置默认请求头
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SetDefaultHeaders(string name, string value)
        {
            _httpClient?.DefaultRequestHeaders.Add(name, value);
        }

        /// <summary>
        /// 删除默认请求头
        /// </summary>
        /// <param name="name"></param>
        public void RemoveDefaultHeaders(string name)
        {
            _httpClient?.DefaultRequestHeaders.Remove(name);
        }

        /// <summary>
        /// 释放httpclient
        /// </summary>
        public void Release()
        {
            _httpClient?.Dispose();
        }
    }
}

 

标签:封装,string,header,C#,headers,url,new,null,HttpClient
From: https://www.cnblogs.com/yiyeyihua/p/16854275.html

相关文章

  • Elasticsearch安装部署
    本文只分享windows下安装流程安装版本为:elasticsearch-8.4.3kibana-8.4.3kibana汉化   双击运行 bin文件下的elas......
  • clip-path属性深入理解与使用
      clip-pathCSS属性可以创建一个只有元素的部分区域可以显示的剪切区域。区域内的部分显示,区域外的隐藏。clip-path的属性值可以是以下几种:1.inset; 将元素剪裁为......
  • 施耐德PLC如何实现组态监控和远程维护?
    工业组态是一种可以反映工艺流程、实现远程监控的系统软件,在很多工业领域都有使用。组态软件设备作为上位机,可以连接PLC、仪器仪表、智能模块等等设备或第三方软件,为企业提......
  • shell结合expect 脚本自动备份华为交换机配置文件
    最近看了点expect的知识点,就产生了个利用它来自动备份交换机配置的想法。于是就做了下尝试。来看看如何实现。Expect是一个用来实现自动交互功能的软件套件,是基于TCL的脚......
  • LVS + keepalived + nginx + tomcat 实现主从热备 + 负载均衡
    前言首先声明下,由于这两天找资料,看了不少博客,但是出于不细心,参考者的博客地址没有记录下来,所有文中要是出现了与大家博客相同的地方,那么请大家在评论区说明并附上博客......
  • React Native 锚点 ScrollView 实现
    引用:<AnchoranchorList={anchorContentCultureList}initCurIndex='shiming'/> Anchor.tsx代码//社区Tab下文化Tab页锚点importReact,{Rea......
  • 机器学习100天( 100-Days-Of-ML-Code )中文版
    机器学习AI算法工程 公众号: datayx完整版下载地址获取:关注微信公众号datayx 然后回复 100  即可获取。数据预处理|第1天数据预处理实现简单线性回归|第2天简单......
  • 从0开始梳理django项目_1.始于docker
    基础准备看了篇文章,对比了一些构建django项目的docker环境,发觉自己以前了解的不够全面。这次尝试其中4个。不太记得构建dockerfile文件的书写了,后边还要升级到comp......
  • keepalived实现mycat高可用问题排查;道路坎坷,布满荆棘,定让你大吃一惊!
    开心一刻医院里,一母亲带着小女孩打针小女孩:“妈妈我不想打针,疼!”妈妈:“宝贝儿听话,这里这么多护士阿姨,咱们找个打针不疼的”小女孩:“那哪个阿姨打针不疼呢?”......
  • web服务器14 cors跨域资源共享
    通过控制Access-Control-Allow-Origin修改只有哪些网页可以访问资源res.setHeader('Access-Control-Allow-Origin','*')默认情况下,CORS仅支持客户端向服务器发送如下的9......