C# HttpClient使用详解

 HttpClient工具类,实现了Get、Post请求,支持设置超时时间和是否记录错误日志

public class HttpHelper
{
    #region HttpClient 
    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="timeOut">超时时间:默认10s</param>
    /// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
    /// <returns></returns>
    /// <exception cref="HttpRequestException"></exception>
    public static async Task<string> HttpGetAsync(string url, int timeOut = 10, bool isWriteFileLog = true)
    {
        string retString = string.Empty;
        using HttpClient httpClient = new();
        CancellationTokenSource cts = new();
        cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
        CancellationToken cancellationToken = cts.Token;
        try
        {
            HttpResponseMessage response = await httpClient.GetAsync(url, cancellationToken);
            if (response.IsSuccessStatusCode)
            {
                retString = await response.Content.ReadAsStringAsync();
            }
            else
            {
                throw new HttpRequestException($"请求失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            if (isWriteFileLog)
            {
                LogHelper.Error($"get to [{url}] failed for {ex.Message}", typeof(HttpService), "Get请求");
            }
        }
        return retString;
    }


    /// <summary>
    /// post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="data"></param>
    /// <param name="timeOut">超时时间:默认10s</param>
    /// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
    /// <returns></returns>
    public static async Task<string> HttpPostAsync(string url, string data, int timeOut = 10, bool isWriteFileLog = true)
    {
        string retString = string.Empty;
        using HttpClient httpClient = new();
        CancellationTokenSource cts = new();
        cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
        CancellationToken cancellationToken = cts.Token;
        StringContent content = new(data, Encoding.UTF8, "application/json");
        try
        {
            HttpResponseMessage response = await httpClient.PostAsync(url, content, cancellationToken);
            if (response.IsSuccessStatusCode)
            {
                retString = await response.Content.ReadAsStringAsync();
            }
            else
            {
                throw new HttpRequestException($"请求失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            if (isWriteFileLog)
            {
                LogHelper.Error($"post to [{url}] failed for {ex.Message},data is {data}", typeof(HttpService), "Post请求");
            }
        }
        return retString;
    }

    /// <summary>
    /// post表单提交
    /// </summary>
    /// <param name="url"></param>
    /// <param name="dic"></param>
    /// <param name="timeOut">超时时间:默认10s</param>
    /// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
    /// <returns></returns>
    public static async Task<string> HttpPostAsync(string url, Dictionary<string, string> dic, int timeOut = 100, bool isWriteFileLog = true)
    {
        string retString = string.Empty;
        using HttpClient httpClient = new();
        CancellationTokenSource cts = new();
        cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
        CancellationToken cancellationToken = cts.Token;
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
        var content = new FormUrlEncodedContent(dic);
        try
        {
            HttpResponseMessage response = await httpClient.PostAsync(url, content, cancellationToken);
            if (response.IsSuccessStatusCode)
            {
                retString = await response.Content.ReadAsStringAsync();
            }
            else
            {
                throw new HttpRequestException($"请求失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            if (isWriteFileLog)
            {
                LogHelper.Error($"post to [{url}] failed for {ex.Message},dic is {JsonConvert.SerializeObject(dic)}", typeof(HttpService), "Post表单提交");
            }
        }

        return retString;
    }
    #endregion
}

Log日志功能请跳转:C# Log日志功能-CSDN博客

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值