C# 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();
        }
    }
}
复制代码

 

posted @   一叶一花  阅读(681)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示