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


    版权声明:本文为博主原创文章,遵循 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);
            }
        }
    }
  • 相关阅读:
    Linux下数据库备份恢复过程
    BMC 安装操作系统以及 驱动的处理
    vCenter简单查看多少虚拟机在开机状态和一共多少虚拟机
    PDB自动启动以及Oracle Pfile的参数修改示范
    Oracle 测试环境 数据库安装过程
    CentOS Mininal 安装VMtools的方法
    日常工作 数据库中表与索引占用磁盘的简单分析
    Oracle数据库 查看表是否是 索引组织表的方法
    zabbix 使用问题两个--中文乱码,以及监控ESXi下的虚拟机
    Zabbix的简单使用
  • 原文地址:https://www.cnblogs.com/superfeeling/p/11577371.html
Copyright © 2020-2023  润新知