HttpWebRequest模拟数据提交

2007年07月24日  |  2:55 下午分类:Develop  |  

这段时间,有不少朋友问我,如果用程序向一个页面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文件内容,已实现数据的提交。

转载时务必以超链接形式标明文章原始出处和作者信息。

相关文章

  • 暂无相关日志

3 位领导已批示 关于 “HttpWebRequest模拟数据提交”

  1. 小串 发表于: 七月 24th, 2007 3:27 下午

    用异步提交吧

  2. 幻想曲 发表于: 七月 24th, 2007 3:29 下午

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

  3. overred 发表于: 七月 25th, 2007 11:51 下午

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

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

    ^+^


发表您的评论

1410168172122013183195114157619