Httpclient Post Webapi

Httpclient Post Webapi

格式:
application/x-www-form-urlencoded 提交的数据按照 key1=val1&key2=val2 的方式进行编码
multipart/form-data 必须让 表单的 enctype 等于 multipart/form-data,可以传键值对,也可以上传文件
原生 表单也只支持这两种方式(通过 元素的 enctype 属性指定,默认为 application/x-www-form-urlencoded)
application/json json一般是接收格式,也可以作为提交格式,使用StringContent方法,服务器端需要对应处理,一般应对格式复杂数据
参数:
.net 提交参数以KeyValuePair 集合形式,可以使用Dictionary,使用FormUrlEncodedContent方法创建httpcontent
在这里插入图片描述

        private void btn_post_Click(object sender, EventArgs e)
        {
            string url = @"http://api.apishop.net/common/joke/getJokesByRandom";
            HttpClient client = new HttpClient();

            var values = new Dictionary<string, string>
            {
               { "apiKey", "***********" },
               { "pageSize", "3" }
            };
            var content = new FormUrlEncodedContent(values);
            HttpResponseMessage response = client.PostAsync(url, content).Result;
            response.EnsureSuccessStatusCode();
            string responseBody = response.Content.ReadAsStringAsync().Result;

            
            //string json = JsonConvert.SerializeObject(new {
            //    apiKey = "",
            //    pageSize = "3"
            //});
            //var content = new StringContent(json, Encoding.UTF8, "application/json");
            //HttpResponseMessage response = client.PostAsync(url, content).Result;
            //string responseBody = response.Content.ReadAsStringAsync().Result;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值