5月,我们的纪念
这段时间,有不少朋友问我,如果用程序向一个页面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文件内容,已实现数据的提交。
Categories:   学以致用
Tags:  
Actions:   Comments (7) |

Comments

1#

July 24 2007 , 14:27

小串

用异步提交吧

小串 | Top

2#

July 24 2007 , 14:29

幻想曲

只是简要说明,呵呵
实际在应用就要异步啦

幻想曲 | Top

3#

July 25 2007 , 22:51

overred

----广告开始-----
本人承接各种数据采集活哈哈
搞这种数据采集长达半年

验证码识别 模拟登陆
----广告结束-------

^+^

overred | Top

4#

July 29 2007 , 13:00

妞妞

如果用程序向一个页面Post数据?

如何用程序向一个页面Post数据?

妞妞 | Top

5#

July 29 2007 , 13:09

幻想曲

[quote=妞妞]
如果用程序向一个页面Post数据?

如何用程序向一个页面Post数据?
[/quote]
该文讲的就是这啊~~~

幻想曲 | Top

6#

August 11 2007 , 08:35

llinzzi

"指定好Active及Method"晕倒 action拉
用HttpWebRequest提交不过瘾的,幻想兄可以试着用socket提交试试,可以对http协议进一步了解 :)

llinzzi | Top

7#

August 11 2007 , 17:29

幻想曲

已修正,thx

幻想曲 | Top

Add comment



(Will show your Gravatar icon)  



  Country flag


[b][/b] - [i][/i] - [u][/u]- [quote][/quote]

:-/ ^_^ :d :o :kiss: :) :p :se: [yeah] :( :love: :han: :up: :cry: :zzz: o_o


申请链接请看这里