zoukankan      html  css  js  c++  java
  • 使用HttpClient和WebRequest时POST一个对象的写法

    【一】步骤:

    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);
                }
            }
  • 相关阅读:
    SVN 、Git、Github的使用
    asp.net core 系列 8 Razor框架路由(下)
    asp.net core 系列 7 Razor框架路由(上)
    asp.net core 系列 6 MVC框架路由(下)
    asp.net core 系列 5 MVC框架路由(上)
    asp.net core 系列 4 注入服务的生存期
    asp.net core 系列 3 依赖注入服务
    asp.net core 系列 2 启动Startup类介绍
    asp.net core 系列 1 概述
    iframe和response.sendRedirect()跳转到父页面的问题
  • 原文地址:https://www.cnblogs.com/ServiceboyNew/p/5250922.html
Copyright © 2011-2022 走看看