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

posted @ 2023-02-01 20:40  最后的鲨掉  阅读(100)  评论(0)    收藏  举报