C#中POST数据和接收的几种方式(抛砖引玉)

本文介绍了C#中除了HTML表单提交外的POST数据方式,包括使用HttpClient对象发送数据和以键值对方式POST。同时,讨论了不同ContentType(如application/x-www-form-urlencoded、multipart/form-data、application/json、text/xml)下的数据格式,并提及了接收数据的方法,如从InputStream读取并解析。最后,鼓励读者分享更多发送和接收HTTP POST数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POST方式提交数据,一种众所周知的方式:

html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[""]来获取。

 

这里介绍另外一种POST方式和接收方式,就是将整个数据作为加入到数据流中提交和接收

接收方式:

Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
return Encoding.UTF8.GetString(b);

只需要从input Stream中读取byte数据,然后转为string,再解析即可。如果要回复响应消息只需要用:Response.Write()  输出即可(和普通的页面输出一样)。

 

主动POST发送方式:

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();



            using (var httpWebResponse = webrequest.GetResponse())
            using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
            {

                String ret = responseStream.ReadToEnd();

                T result = XmlDeserialize<T>(ret);

                return result;
            }

使用HttpClient对象发送

 public static  string   PostXmlResponse(string url, string xmlString)
             
        {
            HttpContent httpContent = new StringContent(xmlString);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpClient httpClient = new HttpClient();

           

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                return t.Result;
            }
            return string.Empty;
        }
         

 

从代码中可以看出仅仅是将字符串转为byte[] 类型,并加入到请求流中,进行请求即可达到POST效果,该种POST方式与上边所提到的接收方式相互配合使用。

下面一种方式是以键值对的方式主动POST传输的。

 

     /// <summary>
        /// 发起httpPost 请求,可以上传文件
        /// </summary>
        /// <param name="url">请求的地址</param>
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值