.net发送post请求的两种方法

本文介绍了一个使用C#进行HTTP POST请求的例子,演示了如何通过WebRequest和HttpClient两种方式发送带参数的POST请求,并接收服务器返回的数据。
 public void HttpTestMe()
        {
            string url7 = "http://localhost:2810/Login/login";
            WebRequest request7 = WebRequest.Create(url7);
            request7.Method = "POST";

            //post传参数
            string postdata = "LoginName=365admin&Password=fob123";
            byte[] bytes = Encoding.ASCII.GetBytes(postdata);
            request7.ContentType = "application/x-www-form-urlencoded";
            request7.ContentLength = postdata.Length;
            Stream sendStream = request7.GetRequestStream();
            sendStream.Write(bytes, 0, bytes.Length);
            sendStream.Close();

            //得到返回值
            WebResponse response7 = request7.GetResponse();
            string OrderQuantity = new StreamReader(response7.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();

            //转化成json对象处理
            //List<GetOrderQuantity> getOrderQuantity = sr.Deserialize<List<GetOrderQuantity>>(OrderQuantity);


            //方法二:需要添加using System.Net.Http;的引用
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:2810");
                var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("LoginName", "365admin"), new KeyValuePair<string, string>("Password", "fob123")});
                var result = client.PostAsync("/Login/login", content).Result;
                string resultContent = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(resultContent);
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值