HttpClient类 封装

文章详细介绍了如何在C#中使用HttpClientUtil类进行HTTP请求,包括同步和异步的POST、GET方法,以及文件上传功能,使用了JsonConvert处理JSON数据。
摘要由CSDN通过智能技术生成
 public static class HttpClientUtil
    {
        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static string HttpPost(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string>? headers = null)
        {
            
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {
                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;
                }
            }
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string>? headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {
                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 = await client.PostAsync(url, httpContent);
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static T? HttpPost<T>(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string>? headers = null)
        {
            return HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<T?> HttpPostAsync<T>(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string>? headers = null)
        {
            var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
            return res.ToEntity<T>();
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T? HttpGet<T>(string url, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            return HttpGet(url, contentType, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<T?> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            var res = await HttpGetAsync(url, contentType, headers);
            return res.ToEntity<T>();
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public static string UploadFile(string url, string fileUrl)
        {
            Stream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
            var formData = new MultipartFormDataContent();
            byte[] data = new byte[fileStream.Length];
            fileStream.Read(data, 0, data.Length);
            formData.Add(new StreamContent(fileStream),"file", fileUrl);

            // 实例化HttpClient
            using (HttpClient client = new HttpClient())
            { 
                // 发送请求
                HttpResponseMessage result = client.PostAsync(url, formData).Result;
                // 接受结果
                string responseResult = result.Content.ReadAsStringAsync().Result;
                // 打印结果
                Console.WriteLine(responseResult);
                client.Dispose();
                fileStream.Close();
                return responseResult;
            }
        }
    }


    /// <summary>
    /// Json扩展方法
    /// </summary>
    public static class JsonExtends
    {
        public static T? ToEntity<T>(this string val)
        {
            return JsonConvert.DeserializeObject<T>(val);
        }

        //public static List<T> ToEntityList<T>(this string val)
        //{
        //    return JsonConvert.DeserializeObject<List<T>>(val);
        //}
        public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
        {
            return JsonConvert.SerializeObject(entity, formatting);
        }
    }



Console.WriteLine("===========================================================");
Console.WriteLine("================后台模拟Http请求调用Api====================");
Console.WriteLine("===========================================================");

try
{
    

    //get请求
    string userResult = HttpClientUtil.HttpGet("https://www.baidu.com/");

    //post请求
    string parameter = Newtonsoft.Json.JsonConvert.SerializeObject(new User()
    {
        Id = 234,
        Name = "Richard",
        Age = 37
    });
    string result = HttpClientUtil.HttpPost("https://www.baidu.com/", parameter);

    //文件上传
    string uploadResult = HttpClientUtil.UploadFile("https://www.baidu.com/", "这里是一个文件上传的测试文件.doc");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值