C# 客户端网络请求 对HttpClient的封装

在写C#客户端程序时,或者在服务之间调用API时,我们往往会用到HttpClient来进行交互,这里我做了下简单的二次封装,并不定期更新。

下面是整个封装的HttpClient帮助类:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    /// <summary>
    /// Summary: HttpClient公共类
    /// Author: Lee Liu
    /// Date: 20190114
    /// </summary>
    public class HttpClientHelper
    {
        private static HttpClientHelper httpClientHelper = null;

        private HttpClient httpClient;

        /// <summary>
        /// 构造方法私有,用于单例
        /// </summary>
        private HttpClientHelper() { }

        /// <summary>
        /// 获取当前类的实例
        /// </summary>
        /// <returns></returns>
        public static HttpClientHelper GetInstance()
        {
            if (httpClientHelper != null)
            {
                return httpClientHelper;
            }
            else
            {
                HttpClientHelper httpClientHelper = new HttpClientHelper();

                //取消使用默认的Cookies
                HttpClientHandler handler = new HttpClientHandler() { UseCookies = false };
                httpClientHelper.httpClient = new HttpClient(handler);
                return httpClientHelper;
            }
        }

        /// <summary>
        /// Get方法请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public HttpResponseMessage Get(string url, List<KeyValuePair<string, string>> headers = null)
        {
            HttpRequestMessage request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };
            if (headers != null && headers.Count > 0)
            {
                request.Headers.Clear();

                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);

                }
            }
            HttpResponseMessage response = httpClient.SendAsync(request).Result;
            return response;
        }

        /// <summary>
        /// Get方法请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GetAsync(string url, List<KeyValuePair<string, string>> headers = null)
        {
            HttpRequestMessage request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };
            if (headers != null && headers.Count > 0)
            {
                request.Headers.Clear();
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            return await httpClient.SendAsync(request);
        }

        /// <summary>
        /// Post方法请求 application/x-www-form-urlencoded格式
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="paramList">参数集合</param>
        /// <returns></returns>
        public HttpResponseMessage Post(string url, List<KeyValuePair<String, String>> paramList, List<KeyValuePair<string, string>> headers = null)
        {
            FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(paramList);
            if (headers != null && headers.Count > 0)
            {
                formUrlEncodedContent.Headers.Clear();
                foreach (var header in headers)
                {
                    formUrlEncodedContent.Headers.Add(header.Key, header.Value);
                }
            }
            HttpResponseMessage response = httpClient.PostAsync(new Uri(url), formUrlEncodedContent).Result;
            return response;
        }

        public async Task<HttpResponseMessage> PostAsync(string url, List<KeyValuePair<String, String>> paramList, List<KeyValuePair<string, string>> headers = null)
        {
            FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(paramList);
            if (headers != null && headers.Count > 0)
            {
                formUrlEncodedContent.Headers.Clear();
                foreach (var header in headers)
                {
                    formUrlEncodedContent.Headers.Add(header.Key, header.Value);
                }
            }
            return await httpClient.PostAsync(new Uri(url), formUrlEncodedContent);
        }

        /// <summary>
        /// Post方法请求 raw data
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="content">raw data</param>
        /// <returns></returns>
        public HttpResponseMessage Post(string url, string content, List<KeyValuePair<string, string>> headers = null)
        {
            StringContent stringContent = new StringContent(content, Encoding.UTF8);
            if (headers != null && headers.Count > 0)
            {
                stringContent.Headers.Clear();
                foreach (var header in headers)
                {
                    //if (!header.Key.ToLower().Contains("accept") && header.Key!= "Cache-Control" && header.Key!= "Connection" && header.Key!= "Host" &&  header.Key != "User-Agent")
                    //{
                    //    stringContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    //}
                    stringContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            HttpResponseMessage response = httpClient.PostAsync(new Uri(url), stringContent).Result;
            return response;
        }

        /// <summary>
        /// Post方法请求 raw data
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="content">raw data</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostAsync(string url, string content, List<KeyValuePair<string, string>> headers = null)
        {
            StringContent stringContent = new StringContent(content, Encoding.UTF8);
            if (headers != null && headers.Count > 0)
            {
                stringContent.Headers.Clear();
                foreach (var header in headers)
                {
                    stringContent.Headers.Add(header.Key, header.Value);
                }
            }
            return await httpClient.PostAsync(new Uri(url), stringContent);

        }

        public HttpResponseMessage Post(string url, object data)
        {
            using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url))
            {
                httpRequestMessage.Content = new ObjectContent<object>(data, new JsonMediaTypeFormatter());
                HttpResponseMessage result = httpClient.SendAsync(httpRequestMessage).Result;
                return result;
            }
        }

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



        /// <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);
        }
    }
}

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值