记录一个C#/.NET的HTTP工具类

发布于:2025-06-28 ⋅ 阅读:(15) ⋅ 点赞:(0)

记录一个C#/.NET的HTTP工具类

using Serilog;
using System.Net;
using System.Text;
using System.Text.Json;

namespace UProbe.Common.Comm.Http
{
    public class HttpClientHelper
    {
        /// <summary>
        /// 发送HttpGet请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T? HttpGet<T>(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                try
                {
                    var response = client.GetAsync(url).Result;
                    if (response != null && response.StatusCode == HttpStatusCode.OK)
                    {
                        var responseStr = response.Content.ReadAsStringAsync().Result;
                        if (string.IsNullOrEmpty(responseStr) == false)
                        {
                            return JsonSerializer.Deserialize<T>(responseStr);
                        }
                    }
                    else
                    {
                        Log.Warning($"请求异常 url={url},status={response?.StatusCode}");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"请求异常 url={url},{ex.ToString()}");
                }
                return default(T);
            }
        }

        /// <summary>
        /// 发送HttpPost请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T? HttpPost<T>(string url, string content = "")
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(content, Encoding.UTF8, "application/json");
                try
                {
                    var response = client.Send(request);
                    if (response != null && response.StatusCode == HttpStatusCode.OK)
                    {
                        var responseStr = response.Content.ReadAsStringAsync().Result;
                        if (string.IsNullOrEmpty(responseStr) == false)
                            return JsonSerializer.Deserialize<T>(responseStr);
                    }
                    else
                    {
                        Log.Warning($"请求异常 url={url},content={content},status={response?.StatusCode}");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"请求异常 url={url},content={content},{ex.ToString()}");
                }
                return default(T);
            }
        }

        /// <summary>
        /// 发送HttpPost请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static HttpResult<T> HttpPostX<T>(string url, string content = "", string token = "")
        {
            var returnDto = new HttpResult<T>();
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(content, Encoding.UTF8, "application/json");
                if (!string.IsNullOrEmpty(token))
                {
                    request.Headers.Add("Authentication", token);
                }

                try
                {
                    var response = client.Send(request);
                    return HandleResopnse<T>(response);
                }
                catch (Exception ex)
                {
                    Log.Error($"请求异常 url={url},content={content},msg={ex.ToString()}");
                }
                return returnDto;
            }
        }

        /// <summary>
        /// 发送HttpPost请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static HttpResult<T> HttpGetX<T>(string url, string token = "")
        {
            var returnDto = new HttpResult<T>();
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                if (!string.IsNullOrEmpty(token))
                {
                    request.Headers.Add("Authentication", token);
                }

                try
                {
                    var response = client.Send(request);
                    return HandleResopnse<T>(response);
                }
                catch (Exception ex)
                {
                    Log.Error($"请求异常 url={url},msg={ex}");
                }
                return returnDto;
            }
        }


        public static HttpResult<T> HandleResopnse<T>(HttpResponseMessage response)
        {
            var returnDto = new HttpResult<T>();
            if (response != null && response.StatusCode == HttpStatusCode.OK)
            {
                returnDto.StatusCode = 200;
                returnDto.IsSuccess = true;
                returnDto.Msg = "请求成功";
                var responseStr = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseStr) == false)
                {
                    var responseObj = JsonSerializer.Deserialize<T>(responseStr);
                    returnDto.Result = responseObj;
                }
            }
            else if (response != null && response.StatusCode == HttpStatusCode.Unauthorized)
            {
                returnDto.StatusCode = 401;
                returnDto.IsSuccess = false;
                returnDto.Msg = "未认证";
                var responseStr = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseStr) == false)
                {
                    returnDto.Msg += $":{responseStr}";
                }
                Log.Warning($"请求异常 status={response?.StatusCode},返回信息={responseStr}");
            }
            else
            {
                returnDto.IsSuccess = false;
                returnDto.StatusCode = response == null ? 500 : (int)response.StatusCode;
                returnDto.Msg = "请求异常";
                var responseStr = response?.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseStr) == false)
                {
                    returnDto.Msg += $":{responseStr}";
                }
                Log.Warning($"请求异常 status={response?.StatusCode},返回信息={responseStr}");
            }
            return returnDto;
        }

    }
}


网站公告

今日签到

点亮在社区的每一天
去签到