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类,大同小异!

 回到目录

posted @   张占岭  阅读(76916)  评论(21编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2012-10-23 编译器错误~写JS还是谨慎点好
2012-10-23 编译器错误~不能向ObjectStateManager添加相同的键
2012-10-23 编译器错误~System.Data.Objects.DataClasses.EntityObject在未被引用的程序集中定义
点击右上角即可分享
微信分享提示