C# HTTP发送Get和Post 请求

FlurlHttpClient 类

public class FlurlHttpClient
{
    private readonly FlurlClient client;

    public FlurlHttpClient(FlurlClient client)
    {
        this.client = client;
    }

    public async Task<T> GetAsync<T>(string url) where T : class
    {
        try
        {
            return await client.Request(url).GetJsonAsync<T>();
        }
        catch (FlurlHttpException ex)
        {
            string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
            IFlurlResponse? response = ex.Call.Response;
            int? statusCode = response is null ? null : response.StatusCode;//服务器状态码
            string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method},入参:无;message:{ex.Message}";
            throw new Exception(errorMsg);
        }
    }
   
    /// <summary>
    /// Get请求
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url">url</param>
    /// <param name="values">参数以对象的形式传入</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<T> GetAsync<T>(string url, object values)
    {
        try
        {
            return await client.Request(url).SetQueryParams(values).GetJsonAsync<T>();
        }
        catch (FlurlHttpException ex)
        {
            string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
            IFlurlResponse? response = ex.Call.Response;
            string? statusCode = response is null ? null : response.StatusCode.ToString();//服务器状态码
            string errorMsg = $"服务器状态码:{statusCode ?? "无"};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";
            throw new Exception(errorMsg);
        }
    }


    /// <summary>
    /// Post请求
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url">url</param>
    /// <param name="values">参数以对象的形式传入</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<T> PostAsync<T>(string url,object values)
    {
        try
        {
            //.ReceiveJson<T>()方法来指定响应的JSON数据会被反序列化为类型T
            return await client.Request(url).PostJsonAsync(values).ReceiveJson<T>();
        }
        catch (FlurlHttpException ex)
        {
            string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
            IFlurlResponse? response = ex.Call.Response;
            int? statusCode = response is null ? null : response.StatusCode;//服务器状态码
            string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";
            throw new Exception(errorMsg);
        }

    }
}

注入FlurlHttpClient类

/// <summary>
/// 初始化flurlhttpclient
/// </summary>
/// <param name="builder"></param>
public static void InitFlurlHttpClient(this WebApplicationBuilder builder)
{
    var baseUrl = builder.Configuration["wmsBaseUrl"];
    if (string.IsNullOrEmpty(baseUrl)) throw new Exception("baseUrl未配置");

    //WithHeader添加请求头
    builder.Services.AddScoped(provider => new FlurlClient(baseUrl).WithHeader("test","111"));

    builder.Services.AddScoped(provider => {
        var flurlClient = provider.GetService<FlurlClient>(); // 从依赖注入容器中获取 FlurlClient 类型
        if (flurlClient is null) throw new Exception("系统错误flurlClient类还未注入");
        return new FlurlHttpClient(flurlClient);
    });
}

使用

[HttpGet]
public async Task<ActionResult<ApiResponse>> Get()
{
    var resAsync = httpClient.GetAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });
    return this.Success(resAsync);
}
[HttpPost]
public async Task<ActionResult<ApiResponse>> Post()
{
    var resAsync = httpClient.PostAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });
    return this.Success(resAsync);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值