首页 > 其他分享 >HttpClient 正确使用方法

HttpClient 正确使用方法

时间:2023-02-01 20:44:27浏览次数:54  
标签:正确 Get httpResponseMessage HttpTypeEnum HttpMethod var new 方法 HttpClient

如何 正确模拟 Http请求,建议使用HttpClient

 

错误用法

    

var httpClient=new HttpClient();

 

正确用法

ServiceCollection.AddHttpClient();

 

public class Http: IHttp
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IJsonContext _jsonContext;
        public Http(IServiceContext serviceContext)
        {
            _jsonContext = serviceContext.GetRequiredService<IJsonContext>();
            _httpClientFactory = serviceContext.GetRequiredService<IHttpClientFactory>();
        }


        public async Task<TResponse> ExecuteAsync< TResponse>(HttpTypeEnum httpType, string url, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient();

                HttpMethod httpMethod = httpType switch
                {
                    HttpTypeEnum.Get => HttpMethod.Get,
                    HttpTypeEnum.Patch => HttpMethod.Get,
                    HttpTypeEnum.Post => HttpMethod.Get,
                    HttpTypeEnum.Put => HttpMethod.Get,
                    HttpTypeEnum.Delete => HttpMethod.Get,
                    _ => HttpMethod.Get,
                };
                var httpRequestMessage = new HttpRequestMessage(httpMethod, url);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        httpRequestMessage.Headers.Add(header.Key, header.Value);
                    }
                }

                httpClient.Timeout = TimeSpan.FromSeconds(120);
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    var responseJson = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken);
                    var response = _jsonContext.Deserialize<TResponse>(responseJson);
                    if (response is null)
                    {
                        throw new GrowHttpException($"接口请求错误,序列化错误 {responseJson}");
                    }
                    return response;
                }
                else
                {
                    throw new GrowHttpException($"接口请求错误,错误代码{httpResponseMessage.StatusCode},错误原因{httpResponseMessage.ReasonPhrase}");
                }
            }
            catch (GrowHttpException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new GrowHttpException($"客户端调用异常:{ex.Message},接口地址:{url},调用堆栈{ex.StackTrace}");
            }
        }


        public async Task<TResponse> ExecuteAsync<TRequest, TResponse>(HttpTypeEnum httpType, string url, TRequest request, Dictionary<string, string>? headers=null, CancellationToken cancellationToken = default)
        {
            try
            {
                if (request is null)
                {
                    throw new GrowHttpException($"接口请求错误, {nameof(request)} is null");
                }
                var requestJson = _jsonContext.Serialize(request);
                if (requestJson is null)
                {
                    throw new GrowHttpException($"接口请求错误,序列化错误 {nameof(request)}");
                }
                var httpClient = _httpClientFactory.CreateClient();
                HttpMethod httpMethod = httpType switch
                {
                    HttpTypeEnum.Get => HttpMethod.Get,
                    HttpTypeEnum.Patch => HttpMethod.Get,
                    HttpTypeEnum.Post => HttpMethod.Get,
                    HttpTypeEnum.Put => HttpMethod.Get,
                    HttpTypeEnum.Delete => HttpMethod.Get,
                    _ => HttpMethod.Get,
                };
                var httpRequestMessage = new HttpRequestMessage(httpMethod, url);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        httpRequestMessage.Headers.Add(header.Key, header.Value);
                    }
                }

                httpRequestMessage.Content = new StringContent(requestJson);

                httpClient.Timeout = TimeSpan.FromSeconds(120);
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    var responseJson = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken);
                    var response = _jsonContext.Deserialize<TResponse>(responseJson);
                    if (response is null)
                    {
                        throw new GrowHttpException($"接口请求错误,序列化错误 {responseJson}");
                    }
                    return response;
                }
                else
                {
                    throw new GrowHttpException($"接口请求错误,错误代码{httpResponseMessage.StatusCode},错误原因{httpResponseMessage.ReasonPhrase}");
                }
            }
            catch (GrowHttpException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new GrowHttpException($"客户端调用异常:{ex.Message},接口地址:{url},调用堆栈{ex.StackTrace}");
            }
        }



      
    }

  

 通过依赖注入 通过IHttpClientFactory  使用连接池复用HttpClient

标签:正确,Get,httpResponseMessage,HttpTypeEnum,HttpMethod,var,new,方法,HttpClient
From: https://www.cnblogs.com/GoodDog/p/17084109.html

相关文章

  • LabVIEW|小技巧1:秒破加密的vi文件方法
    可以利用专门的网站进行vi文件的解密,网站如下:​​https://www.hmilch.net/h/labview​​步骤:点击-选择按钮->空白框里输入“YES"->点击-提交;成功后下载解密的vi文件(注:此vi文......
  • C# DataTable中Compute方法用法集锦(数值/字符串/运算符/表等操作)
    DataTabledt=newDataTable();//嵌套的三元运算牛叉到五体投地objectobj=dt.Compute("iif(1000=5,1000,iif(100>100,4001,2000))",null);Response.Write(obj);......
  • 大一寸照片的尺寸是多少?一寸照片拍摄方法分享!​
    大一寸照片的尺寸是多少?很多小伙伴日常在生活和学习中,都需要接触我们日常所说的证件照,那么证件照也分非常多的尺寸,如我们最常说的一寸照片,还有二寸照片等等,当然小伙伴们不可......
  • Windows设置电脑定时关机的简单方法(干货)
    卓越电脑定时关机软件是一款操作简便,功能强大,绿色,无任何插件的电脑自动定时关机软件,是家长,公司文员和电脑办公人员的好助手。win7win8 win10win11电脑系统通用卓越电......
  • branch和tag同名的删除方法
    git删除远端分支,一般使用方法 gitpushorigin:branchName gitpushorigin-dbranchNamegit删除远端tag,一般使用gitpushorigintag-dtagName......
  • Spring开启@Async异步方法(javaconfig配置)
    在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。应用场景:某些耗时较长的......
  • sql优化的几种方法
    在sql查询中为了提高查询效率,我们常常会采取一些措施对查询语句进行sql优化,下面总结的一些方法,有需要的可以参考参考。1.对查询进行优化,应尽量避免全表扫描,首先应考虑在whe......
  • 使用Mockito 对方法中的私有void方法
    这里用一段代码举例publicvoidruleJudgement(LongtenantId,LongproductId,LongequipId,List<ModelAttributeValue>modelAttributeValues,List<EquipReportValue......
  • php读取大文件的方法
    1、使用file函数直接读取$starttime=microtime_float();ini_set('memory_limit','-1');$file="testfile.txt";$data=file($file);$line=count($data);//总行数$las......
  • php类自动装载、链式操作、魔术方法
    1、自动装载实例目录下有3个文件:index.phpload.phptests文件夹tests文件夹里有test1.php<?phpnamespaceTests;classTest1{staticfunctiontest(){......