使用HttpClient和WebRequest時POST一個對象的寫法

【一】步驟:html

1)將對象轉化爲Json字符串。json

2)將Json字符串編碼爲byte數組。api

3)設置傳輸對象(WebRequest或者HttpClient)的ContentType是"application/json"。數組

4)設置傳輸對象的ContentLength=Byte數組的長度。app

5)開始傳輸編碼

6)獲取JSON結果:url

【二】示例代碼:spa

【對於WebRequest而言】code

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而言】orm

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);
            }
        }
相關文章
相關標籤/搜索