用Get 与 Post提交数据是我们经常做的事情,在.net里面是如何实现的呢?
我们知道在Form里面,可以使用post也可以使用get。它们都是method的合法取值。但是,post和get方法在使用上下面几点不同: 1、Get方法通过URL请求来传递用户的输入。Post方法通过另外的形式。 2、Get方式的提交你需要用Request.QueryString来取得变量的值,而Post方式提交时,你必须通过Request.Form来访问提交的内容。
1. get是从服务器上获取数据,post是向服务器传送数据。 2. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。
post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。 3. 对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form(可以缩写为Request)获取提交的数据。 4. get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。 5. get安全性较低,post安全性较高。
下面用Get和Post2种方式演示如何提交数据
GetDataSend Get 提交数据
GetDataReceive 接收get的请求数据
PostDataSend Post 提交数据
PostDataReceive 接收Post的请求数据
string strContent = Request.QueryString[ " Desc " ];
// QueryString可获得url中的参数 string strRes = " This is the response from the server:\r\n "
HttpContext.Current.Response.Clear(); // 清除缓冲区流中的所有内容输出。 HttpContext.Current.Response.Write(strRes); // 将信息写入 HTTP 响应输出流。 HttpContext.Current.Response.Flush(); // 向客户端发送当前所有缓冲的输出。
< asp:Button ID = " Button1 " runat = " server " Text = " Button " onclick = " Button1_Click " />
</ div > </ form >
protected void Button1_Click( object sender, EventArgs e) { string strTitle = TextBox1.Text; string strContent = TextBox2.Text;
try { Encoding encode = Encoding.GetEncoding( " utf-8 " );
string postData = " Title= " + strTitle; string strURL = " http://localhost/Test/PostData/PostDataReceive.aspx " ; postData += ( " &Desc= " + strContent);
byte [] data = encode.GetBytes(postData); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strURL); myRequest.Method = " POST " ; // myRequest.ContentType = "application/x-www-form-unlencoded"; // request.ContentType = "text/xml; charset=utf-8 "; myRequest.ContentType = " application/x-www-form-urlencoded " ; // ContentType很重要! myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream(); newStream.Write(data, 0 , data.Length); newStream.Close(); Response.Redirect( " PostDataReceive.aspx " );
} catch (Exception ex) { Response.Write( " <script>alert(\ "" + ex.Message + " \ " )</script> " ); } }