使用HttpClient和WebRequest时POST一个对象的写法

<p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">【一】步骤:</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">1)将对象转化为Json字符串。</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">2)将Json字符串编码为byte数组。</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">3)设置传输对象(WebRequest或者HttpClient)的ContentType是"application/json"。</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">4)设置传输对象的ContentLength=Byte数组的长度。</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">5)开始传输</p><p style="margin: 10px auto; color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">6)获取JSON结果:</p>
<span style="color: rgb(73, 73, 73); font-size: 14px; line-height: 24.8889px; background-color: rgb(199, 203, 189);">【对于WebRequest而言】</span>
static void SendByWebRequesttoApi()
        {
            WebRequest req = WebRequest.Create("http://localhost:15203/api/ApiDefault");
            var stu = new Student { ID = 1, Name = "董玮" };
            string jsonString = JsonConvert.SerializeObject(stu);
            byte[] objectContent = Encoding.UTF8.GetBytes(jsonString);
            req.ContentLength = objectContent.Length;
            req.ContentType = "application/json";
            req.Method = "POST";
            using (var stream = req.GetRequestStream())
            {
                stream.Write(objectContent, 0, objectContent.Length);
                stream.Close();
            }


            var resp = req.GetResponse();
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string s = sr.ReadToEnd();
                System.Console.WriteLine(s);
            }
        }

【对于HttpClient而言】

复制代码
static void SendByHttpClienttoApi()
        {
            var stu = new { ID = 1, Name = "董玮" };
            using (var client = new HttpClient())
            {
                string jsonString = JsonConvert.SerializeObject(stu);
                byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
                using (StreamContent sc = new StreamContent(new MemoryStream(bytes)))
                {
                    sc.Headers.ContentLength = bytes.Length;
                    sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var result = client.PostAsync("http://localhost:15203/api/ApiDefault", sc).Result;
                    var objectResult = JsonConvert.DeserializeObject<Student>(result.Content.ReadAsStringAsync().Result);
                }

            }
        }
复制代码

另外注意,以上是针对WebApi(WebApi默认是JSON格式数据传输)。如果是MVC的模式,那么默认是表单形式传输。因此:

复制代码
 static void SendByWebRequesttoMVC()
        {
            WebRequest req = WebRequest.Create("http://localhost:15203/Default/DoGetStudent");
            var htmlFormPost = "ID=1&Name=董玮";
            byte[] objectContent = Encoding.UTF8.GetBytes(htmlFormPost);
            req.ContentLength = objectContent.Length;
            req.ContentType = "application/x-www-form-urlencoded";   //必须写!
            req.Method = "POST";
            using (var stream = req.GetRequestStream())
            {
                stream.Write(objectContent, 0, objectContent.Length);
                stream.Close();
            }

            var resp = req.GetResponse();
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string s = sr.ReadToEnd();
                System.Console.WriteLine(s);
            }
        }
复制代码

在HttpClient中,把StreamContent改为FormUrlEncodedContent,传入一个Dictionary<string,string>对象即可:

复制代码
 static void SendByHttpClienttoMVC()
        {
            using (var client = new HttpClient())
            {
                FormUrlEncodedContent fc = new FormUrlEncodedContent(new Dictionary<string, string>() { { "ID", "1" }, { "Name", "董玮" } });
                var result = client.PostAsync("http://localhost:15203/Default/DoGetStudent", fc).Result;
                System.Console.WriteLine(result.Content.ReadAsStringAsync().Result);
            }
        }


www.cnblogs.com/ServiceboyNew


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值