http扩展小插件
支持.net framework4.5.1,.net core2.0及以上
应用层需要引用包Kogel.Net,Nuget上可以下载安装。
或者使用Nuget命令添加包
Install-Package Kogel.Net
(一)注册
如果是.netcore直接可以在启动类中(Startup.cs)中注册
//注册HttpClient services.AddKogelHttpClient();
其他环境直接
//请求操作 IHttpClient httpClient = new HttpClient(); //文件访问操作 IFileClient fileClient = new FileClient();
(二)使用
get请求
var responseText = httpClient.Get("https://www.baidu.com/"); Console.WriteLine(responseText);
post请求
var response = httpClient.Post("https://localhost:44370/api/basic/cost_info/get_list", new { cost_code = "837" }, accessToken); //response.StatusCode//状态码 Console.WriteLine(response.Result);
指定类型返回
var resultResponse = httpClient.Post<ResultResponse<PageList<GetCostInfoListReponse>>>("https://localhost:44370/api/basic/cost_info/get_list", new { cost_code = "837" }, accessToken); Console.WriteLine(JsonConvert.SerializeObject(resultResponse));
自定义请求
//参数 var jsonData = JsonConvert.SerializeObject(new { cost_code = "837" }); var byteArr = Encoding.UTF8.GetBytes(jsonData); //请求头 WebHeaderCollection header = new WebHeaderCollection(); header.Add("Authorization", $"Bearer {accessToken}"); //开始请求 var response = httpClient.Request(new KogelRequest { Method = "post", Url = "https://localhost:44370/api/basic/cost_info/get_list", ContentType = "application/json", PostDataType = PostDataType.Byte, PostDataByte = byteArr, Header = header }); Console.WriteLine(response.Result);
以上方法都支持异步
(三)文件操作
通过IFileClient操作,和IHttpClient同理
文件下载
string path = $"{Directory.GetCurrentDirectory()}\\abc.png"; fileClient.Download("https://localhost:44370/files/abc.png", path);
文件上传
string path = $"{Directory.GetCurrentDirectory()}\\abc.png"; var resultResponse = fileClient.Upload("https://localhost:44370/api/file/uplpad?suffix=png", path, accessToken); Console.WriteLine(JsonConvert.SerializeObject(resultResponse));
(四)使用Aop查看执行的请求
可以监控请求执行的前后,并且只会作用于当前上下文
//aop监听请求(只会作用于当前上下文) //执行前 HttpBase.Aop.OnExecuting += (KogelRequest request) => { //请求的url var url = request.Url; //请求的参数 var param = request.PostDataByte; //其他HttpWebRequest参数基本都有 }; //执行后 HttpBase.Aop.OnExecuted += (KogelRequest request) => { //请求的url var url = request.Url; //请求的参数 var param = request.PostDataByte; //其他HttpWebRequest参数基本都有 };
示例
https://github.com/a935368322/Kogel.Net/blob/master/Kogel.Net.Test/Command/HttpClientCommand.cs
框架开源,完整框架源码可以去Github上下载:
https://github.com/a935368322/Kogel.Net
如有问题也可以加QQ群讨论:
技术群 710217654