码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-12-03 23:07:25      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

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());
            }

        }

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

标签:

原文地址:http://www.cnblogs.com/lijiasnong/p/5017714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!