使用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); } }