打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
WebApi系列~通过HttpClient来调用Web Api接口

WebApi系列~通过HttpClient来调用Web Api接口

HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api的方法,基于api项目的特殊性,它需要有一个完全安全的环境,所以,你的api控制器看起来有点特别,只有5个方法,而且都是标准的http方法,我觉得这种设计很不错,很清晰,而且为了实现安全性,它不支持使用传统的表单数据,取而代之的是FromBody参数,它指拿HttpRequestMessage里参数,而不是所有的Request数据,这是基于安全方面的考虑。

一 Api接口参数的标准性

Get方式,可以有多个重载,有多个参数

POST方式,只能有一个参数,并且用[FromBody]约束,如果有多个参数,需要以对象的方式进行传递

Put方式,只能有两个参数,其中一个是通过Request.QueryString方式进行传递的,作为要更新对象的主键,别一个是[FromBody]字段,也是一个字段,如果多个字段需要把它封装成对象

标准接口如图

二 调用方,参数的标准性

在客户端进行接口调用时,我们以网页端为例,看一下网页端进行ajax跨域请求的代码

Get方式

    $.ajax({            url: "http://localhost:52824/api/register",            type: "GET",            success: function (data) {                console.log("json:" + data);            }        });

Post方式

     $.ajax({            url: "http://localhost:52824/api/register",            type: "POST",            data: { '': '1' },//这里键名称必须为空,多个参数请传对象,api端参数名必须为value            success: function (data) {                console.log("post:" + data);            }        });

三 在控制台中实现Get方式获取接口数据(只有异步实现)

      /// <summary>        /// HttpClient实现Get请求        /// </summary>        static async void dooGet()        {            string url = "http://localhost:52824/api/register?id=1&leval=5";            //创建HttpClient(注意传入HttpClientHandler)            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };            using (var http = new HttpClient(handler))            {                //await异步等待回应                var response = await http.GetAsync(url);                //确保HTTP成功状态值                response.EnsureSuccessStatusCode();                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)                Console.WriteLine(await response.Content.ReadAsStringAsync());            }        }

四 在控制台中实现Post方式提交数据(只有异步实现)

     /// <summary>        /// HttpClient实现Post请求        /// </summary>        static async void dooPost()        {            string url = "http://localhost:52824/api/register";            var userId = "1";            //设置HttpClientHandler的AutomaticDecompression            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };            //创建HttpClient(注意传入HttpClientHandler)            using (var http = new HttpClient(handler))            {                //使用FormUrlEncodedContent做HttpContent                var content = new FormUrlEncodedContent(new Dictionary<string, string>()                       {                  {"", userId}//键名必须为空                 });                //await异步等待回应                var response = await http.PostAsync(url, content);                //确保HTTP成功状态值                response.EnsureSuccessStatusCode();                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)                Console.WriteLine(await response.Content.ReadAsStringAsync());            }        }

五 在控制台中实现Put方式提交数据(只有异步实现)

        /// <summary>        /// HttpClient实现Put请求        /// </summary>        static async void dooPut()        {            string url = "http://localhost:52824/api/register?userid=" + userId;            var userId = "1";            //设置HttpClientHandler的AutomaticDecompression            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };            //创建HttpClient(注意传入HttpClientHandler)            using (var http = new HttpClient(handler))            {                //使用FormUrlEncodedContent做HttpContent                var content = new FormUrlEncodedContent(new Dictionary<string, string>()                       {                   {"", "数据"}//键名必须为空                });                //await异步等待回应                var response = await http.PutAsync(url, content);                //确保HTTP成功状态值                response.EnsureSuccessStatusCode();                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)                Console.WriteLine(await response.Content.ReadAsStringAsync());            }        }

OK,到这里,我们的客户端如何去调用web api就讲完了,事实上,手机端,平板端也是相关的方式去调用的,它们也都有自己的HttpClient类,大同小异!

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
await运算符只能用于异步方法中。请考虑用async修饰符标记此方法,并将其返回类型更改为Task
HttpClient来自官方的JSON扩展方法
ASP.NET Web API与Owin OAuth:调用与用户相关的Web API
Windows8HttpClient
WEB API系列(一):WEB API的适用场景、第一个实例
HttpClient + ASP.NET Web API, WCF之外的另一个选择
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服