这段时间,有不少朋友问我,如果用程序向一个页面Post数据?
在web中,Post数据首先要有一个Form,指定好Action及Method,然后处理页面通过Request获取数据。
<form action="b.aspx" method="post">
<intput type="text" name="aa" />
</form>
b.aspx中
string a = Request.Form["aa"];
即可得到a的值
我们可以用控制台程序、桌面程序来模拟这种数据的提交,在编写代码之前,请先关注该文:
http://support.microsoft.com/kb/290591/zh-cn
.Net中可以用HttpWebRequest来实现,该类在System.Net命名空间中
假定有一个a.aspx页面,a.aspx.cs中代码如下:
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Form["aa"];
string bb = Request.Form["bb"];
using (StreamWriter sw = new StreamWriter(@"C:\222\demo.txt",true))
{
sw.WriteLine(DateTime.Now.ToString() + ":" + s+">>>bb="+bb);
}
}
我们将Post过来的数据写到硬盘的一个文件中。
建一个Console应用程序
class Program
{
static void Main(string[] args)
{
while (true)
{
PostData();
Console.WriteLine("Sending......");
System.Threading.Thread.Sleep(5000);
}
}
private static void PostData()
{
ASCIIEncoding code = new ASCIIEncoding();
string postData = "aa=iceapple.net&bb=yibin.net"; //这是要post的数据
byte[] data = code.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:7662/www/Default.aspx");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; //这里的ContentType很重要!
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream()) //获取数据流,该流是可写入的
{
stream.Write(data, 0, data.Length); //发送数据流
stream.Close();
}
}
}
看demo.txt文件内容,已实现数据的提交。