• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/a1037949156/article/details/90022280
在写C#客户端程序时,或者在服务之间调用API时,我们往往会用到HttpClient来进行交互,这里我做了下简单的二次封装,并不定期更新。

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

using System;
using System.Collections.Generic;
using System.Net.Http;
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)
                {
                    stringContent.Headers.Add(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);
 
        }
 
        /// <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);
        }
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#WCF服务端搭建和客户端调用发布时间:2022-07-14
下一篇:
简简单单学会C#位运算发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap