码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-09-28 22:10:54      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:default   注意   img   media   []   type   code   serialize   def   

【一】步骤:

1)将对象转化为Json字符串。

2)将Json字符串编码为byte数组。

3)设置传输对象(WebRequest或者HttpClient)的ContentType是"application/json"。

4)设置传输对象的ContentLength=Byte数组的长度。

5)开始传输

6)获取JSON结果:

【二】示例代码:

【对于WebRequest而言】

技术分享图片
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);
            }
        }
技术分享图片

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

标签:default   注意   img   media   []   type   code   serialize   def   

原文地址:https://www.cnblogs.com/coce/p/9721034.html

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