提供同步、异步方式执行请求的Http库,模仿axios风格,开源地址:https://gitee.com/guangkuozhihai/LeafHttp。

使用方法:

HttpClient httpClient = new HttpClient();            
httpClient.BaseUrl = "http://localhost:61001"; // 设置基础Url// 同步方式执行请求
ResponseResult res;
ErrorResult err;
bool rst = httpClient.Request(
    new RequestConfig()
    {
        Url = "/Film/GetPagedList",
        Params = new Dictionary<string, object>
        {
            { "page", 1 },
            { "rows", 1 }
        }
    })
    .Execute(out res, out err);
if (rst)
{
    Console.WriteLine("同步方式请求成功,返回数据为:" + res.Data);
}
else
{
    Console.WriteLine("同步方式请求出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
}
// 异步方式执行请求
httpClient.Request(
    new RequestConfig()
    {
        Url = "/Film/UpdateFilmTitle",
        Method = HttpMethods.Post,
        Data = new Dictionary<string, object>
        {
            { "filmId", 1000 },
            { "title", "测试标题" }
        }
    })
    .ExecuteAsync((res) =>
    {
        Console.WriteLine("异步方式请求成功,返回数据为:" + res.Data);
    },
    (err) =>
    {
        Console.WriteLine("异步方式请求出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
    });
// 异步方式执行Get请求
httpClient.Get(
    "/Film/GetPagedList",
    new RequestConfig()
    {
        Params = new Dictionary<string, object>
        {
            { "page", 1 },
            { "rows", 1 }
        }
    })
    .ExecuteAsync((res) =>
    {
        Console.WriteLine("使用别名Get成功,返回数据为:" + res.Data);
    }, (err) =>
    {
        Console.WriteLine("使用别名Get出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
    });
// 异步方式执行Post请求
httpClient.Post(
    "/Film/UpdateFilmTitle",
    new Dictionary<string, object>
    {
        { "filmId", 1000 },
        { "title", "测试标题" }
    })
    .ExecuteAsync((res) =>
    {
        Console.WriteLine("使用别名Post成功,返回数据为:" + res.Data);
    }, (err) =>
    {
        Console.WriteLine("使用别名Post出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
    });
// 上传文件
var uploadFilePath = "D:\\图片\\收藏\\apple.jpg";
httpClient.Post(
    "/File/Upload",
    new Dictionary<string, object>
    {
        { "category", 1 },
        { "file", new FormFile()
            {
                FileName = uploadFilePath,
                FileData = File.ReadAllBytes(uploadFilePath)
            }
        }
    },
    new RequestConfig()
    {
        UseMultipartFormDataPost = true // 请求头的Content-Type自动设置为multipart/form-data
    })
    .ExecuteAsync((res) =>
    {
        Console.WriteLine("上传文件成功,返回数据为:" + res.Data);
    }, (err) =>
    {
        Console.WriteLine("上传文件出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
    });
// 下载文件
var saveFilePath = "D:\\apple.jpg";
httpClient.Get(
    "/da2defca-13d8-4a07-ba47-0b1d67e52c20.jpg",
    new RequestConfig()
    {
        ResponseType = ResponseType.ArrayBuffer
    })
    .ExecuteAsync((res) =>
    {
        File.WriteAllBytes(saveFilePath, res.Data as byte[]);
        Console.WriteLine("下载文件成功,文件保存至:" + saveFilePath);
    }, (err) =>
    {
        Console.WriteLine("下载文件出错,错误信息为:" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
    });

声明拦截器:

// 拦截器需继承于IRequestInterceptor接口
public class RequestInterceptor : IRequestInterceptor
{
    public void Request(RequestConfig config)
    {
        Console.WriteLine("记录请求执行,Url地址:" + config.Url);
    }

    public void RequestError(Exception ex)
    {
        Console.WriteLine("记录请求出错,错误信息:" + ex.Message);
    }

    public void Response(ResponseResult response)
    {
        Console.WriteLine("记录收到回复,状态码为:" + response.Status);
    }

    public void ResponseError(ErrorResult error)
    {
        Console.WriteLine("记录回复出错,状态码为:" + (error.Response != null ? error.Response.Status.ToString() : ""));
    }
}

使用拦截器:

// 向HttpClient实例增加拦截器
var interceptor = new RequestInterceptor();
httpClient.AddInterceptor(interceptor);

 

版权声明:本文为lgyup原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lgyup/p/14550642.html