.net發送post請求的兩種方法

[csharp] view plain copy
  1. public void HttpTestMe()  
  2.        {  
  3.            string url7 = "http://localhost:2810/Login/login";  
  4.            WebRequest request7 = WebRequest.Create(url7);  
  5.            request7.Method = "POST";  
  6.   
  7.            //post傳參數  
  8.            string postdata = "LoginName=365admin&Password=fob123";  
  9.            byte[] bytes = Encoding.ASCII.GetBytes(postdata);  
  10.            request7.ContentType = "application/x-www-form-urlencoded";  
  11.            request7.ContentLength = postdata.Length;  
  12.            Stream sendStream = request7.GetRequestStream();  
  13.            sendStream.Write(bytes, 0, bytes.Length);  
  14.            sendStream.Close();  
  15.   
  16.            //得到返回值  
  17.            WebResponse response7 = request7.GetResponse();  
  18.            string OrderQuantity = new StreamReader(response7.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();  
  19.   
  20.            //轉化成json對象處理  
  21.            //List<GetOrderQuantity> getOrderQuantity = sr.Deserialize<List<GetOrderQuantity>>(OrderQuantity);  
  22.   
  23.   
  24.            //方法二:需要添加using System.Net.Http;的引用  
  25.            using (HttpClient client = new HttpClient())  
  26.            {  
  27.                client.BaseAddress = new Uri("http://localhost:2810");  
  28.                var content = new FormUrlEncodedContent(new[] { new KeyValuePair<stringstring>("LoginName""365admin"), new KeyValuePair<stringstring>("Password""fob123")});  
  29.                var result = client.PostAsync("/Login/login", content).Result;  
  30.                string resultContent = result.Content.ReadAsStringAsync().Result;  
  31.                Console.WriteLine(resultContent);  
  32.            }  
  33.        }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章