c# 模拟Asp.net页面中的某个按钮的点击,向web服务器发出请求
主要就组织要提交的数据,然后以post方式提交。
假设我们有如下的网页


1 <% @ Page Language = " C# "  AutoEventWireup = " true "   CodeFile = " Default.aspx.cs "  Inherits = " _Default" %>
2
3 <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
4
5 < html  xmlns ="http://www.w3.org/1999/xhtml" >
6 < head  runat ="server" >
7 < title > 无标题页 </ title >
8 </ head >
9 < body >
10 < form  id ="form1"  runat ="server" >
11 < div >
12 < table >
13 < tr >
14 < td >  姓名: </ td >< td >< asp:TextBox  ID ="txtName"  runat ="server" ></ asp:TextBox ></ td >
15 </ tr >
16 < tr >
17 < td >  昵称: </ td >< td >< asp:TextBox  ID ="txtPwd"  runat ="server"  TextMode ="Password"  Width="149px" ></ asp:TextBox ></ td >
18 </ tr >
19 </ table >
20 < asp:Button  ID ="btnUpdate"  runat ="server"  Text ="Longon"  OnClick ="btnUpdate_Click"  Width="60px" />
21 < asp:Button  ID ="btnClose"  runat ="server"  OnClick ="btnClose_Click"  Text ="Close" />< br  />
22
23 </ div >
24 </ form >
25 </ body >
26 </ html >

用IE访问这个页面的时候可以得到如下的输出


1
2
3 <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
4
5 < html  xmlns ="http://www.w3.org/1999/xhtml" >
6 < head >< title >
7      无标题页
8 </ title ></ head >
9 < body >
10 < form  name ="form1"  method ="post"  action ="Default.aspx"  id ="form1" >
11 < div >
12 < input  type ="hidden"  name ="__VIEWSTATE"  id ="__VIEWSTATE"  value="/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=" />
13 </ div >
14
15 < div >
16 < table >
17 < tr >
18 < td >  姓名: </ td >< td >< input  name ="txtName"  type ="text"  id ="txtName" /></ td >
19 </ tr >
20 < tr >
21 < td >  昵称: </ td >< td >< input  name ="txtPwd"  type ="password"  id ="txtPwd"  style ="width:149px;" /></ td >
22 </ tr >
23 </ table >
24 < input  type ="submit"  name ="btnUpdate"  value ="Logon"  id ="btnUpdate"  style ="width:60px;" />
25 < input  type ="submit"  name ="btnClose"  value ="Close"  id ="btnClose" />< br  />
26
27 </ div >
28
29 < div >
30
31 < input  type ="hidden"  name ="__EVENTVALIDATION"  id ="__EVENTVALIDATION"  value="/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ" />
32 </ div ></ form >
33 </ body >
34 </ html >
35

由上面的代码可以看出除了txtName,txtPwd以及两个按钮外,多出了两个__VIEWSTATE,__EVENTVALIDATION这四个表单需要提交到的,要模拟哪个按钮,在加上哪个按钮的表单的值就可以了,如:btnUpdate=Logon
在拼接提交的字符串的时候注意一下,用System.Web.HttpUtility.UrlEncode方法转换成Url编码的字符串。
下面是针对这个页面的btnUpdate 按钮的提交数据

1 string  __VIEWSTATE  = " /wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4= " ;
2 string  __EVENTVALIDATION  = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ " ;
3
4 __VIEWSTATE  =  System.Web.HttpUtility.UrlEncode(__VIEWSTATE);
5
6 __EVENTVALIDATION  =  System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);
7
8 string  strPostData  =  String.Format( " __VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3} "
9                             , __VIEWSTATE,  this .txtName.Text,  this .txtPassword.Text, __EVENTVALIDATION
10                             );

然后创建一个HttpWebRequest对象,设置提交方式是post,然后把上面准备的字符串写进请求数据流里
基本上就可以了
如果有需要在访问不同页面时保存Session的话,需要设置HttpWebRequest对象的CookieContainer属性,保证每次设置的CookieContainer都是同一个对象就可以了。
下面是这个类就是向WEB页面发出请求,并得到返回数据的类


  1 using  System;
  2 using  System.Net;
  3
  4 namespace  Dlse.Com.Cn.Why
  5 {
  6 class  WebPageReader
  7 {
  8
  9 /// <summary>
10 ///  cookie
11 /// </summary>
12 private  CookieCollection _Cookies  = new  CookieCollection();
13
14 /// <summary>
15 ///  保持提交到同一个Session
16 /// </summary>
17 private  CookieContainer cookieContainer  = new  CookieContainer();
18
19 /// <summary>
20 ///  保持连接
21 /// </summary>
22 private bool  isKeepAlive  = false ;
23
24 public bool  IsKeepAlive
25 {
26 get {  return  isKeepAlive; }
27 set { isKeepAlive  =  value; }
28          }
29
30
31
32 public string  GetHTML( string  URL)
33 {
34 return  GetHTML(URL,  "" , System.Text.Encoding.ASCII);
35          }
36
37 public string  GetHTML( string  URL,  string  PostData)
38 {
39 return  GetHTML(URL, PostData, System.Text.Encoding.ASCII);
40          }
41
42 public string  GetHTML( string  URL, System.Text.Encoding encoding)
43 {
44 return  GetHTML(URL, "" ,encoding );
45          }
46
47 /// <summary>
48 ///  获取指定地址的html
49 /// </summary>
50 /// <param name="URL"></param>
51 /// <param name="PostData"></param>
52 /// <param name="encoding"></param>
53 /// <returns></returns>
54 public string  GetHTML( string  URL,  string  PostData, System.Text.Encoding encoding)
55 {
56              isKeepAlive  = false ;
57 string  _Html  = "" ;
58
59              HttpWebRequest request  =  (HttpWebRequest)HttpWebRequest.Create(URL);
60              request.Accept  = " image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */* " ;
61
62
63 if  (_Cookies.Count  > 0 )
64 {
65                  request.CookieContainer.Add( new  Uri(URL), _Cookies);
66              }
67 else
68 {
69                  request.CookieContainer  = this .cookieContainer;
70              }
71
72 // 提交的数据
73 if  (PostData  != null &&  PostData.Length  > 0 )
74 {
75                  request.ContentType  = " application/x-www-form-urlencoded " ;
76                  request.Method  = " POST " ;
77
78 byte [] b  =  encoding.GetBytes(PostData);
79                  request.ContentLength  =  b.Length;
80 using  (System.IO.Stream sw  =  request.GetRequestStream())
81 {
82 try
83 {
84                          sw.Write(b,  0 , b.Length);
85                      }
86 catch  (Exception ex)
87 {
88 throw new  Exception( " Post Data Error!! " , ex);
89                      }
90 finally
91 {
92 if  (sw  != null )  { sw.Close(); }
93                      }
94                  }
95              }
96
97
98              HttpWebResponse response  = null ;
99              System.IO.StreamReader sr  = null ;
100
101 try
102 {
103
104                  response  =  (HttpWebResponse)request.GetResponse();
105
106                  _Cookies  =  response.Cookies;
107
108                  sr  = new  System.IO.StreamReader(response.GetResponseStream(), encoding);
109
110                  _Html  =  sr.ReadToEnd();
111
112              }
113 catch  (WebException webex)
114 {
115 if  (webex.Status  ==  WebExceptionStatus.KeepAliveFailure)
116 {
117                      isKeepAlive  = true ;
118                  }
119 else
120 {
121 throw new  Exception( " DownLoad Data Error " , webex);
122                  }
123              }
124 catch  (System.Exception ex)
125 {
126 throw new  Exception( " DownLoad Data Error " , ex);
127              }
128 finally
129 {
130 if  (sr  != null )  { sr.Close(); }
131 if  (response  != null )  { response.Close(); }
132                  response  = null ;
133                  request  = null ;
134              }
135
136 return  _Html;
137
138          }
139      }
140 }
141

使用方法如下


1 private  WebPageReader webReader = new  WebPageReader();
2
3 string  __VIEWSTATE  = " /wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4= " ;
4 string  __EVENTVALIDATION  = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ " ;
5
6 __VIEWSTATE  =  System.Web.HttpUtility.UrlEncode(__VIEWSTATE);
7
8 __EVENTVALIDATION  =  System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);
9
10 string  strPostData  =  String.Format( " __VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3} "
11                              , __VIEWSTATE,  this .txtName.Text,  this .txtPassword.Text, __EVENTVALIDATION
12                              );
13 string  strHTML;
14
15 try
16 {
17 do
18 {
19          strHTML  =  webReader.GetHTML( " http://localhost:3517/WebSite1/Default.aspx " , strPostData);
20      } while  (webReader.IsKeepAlive);
21
22
23 this .richTextBox1.Text  =  strHTML;
24 }
25 catch  (Exception ex)
26 {
27 if  (ex.InnerException  != null )
28 {
29          MessageBox.Show(ex.Message  + " /n " +  ex.InnerException.Message);
30      }
31 else
32 {
33          MessageBox.Show(ex.Message);
34      }
35 }

使用C#模拟ASP.NET页面中按钮点击的更多相关文章

  1. [转] c# 模拟Asp.net页面中的某个按钮的点击,向web服务器发出请求

    在没有做题目中所述的内容的时候,感觉这应该是很简单的东西,但是当真正开始做的时候却发现,有很多问题现在在这里写出来,供和我一样水平不高的参考一下. 在写本文之前参照了一下文章 欢迎使用CSDN论坛阅读 ...

  2. ASP.NET页面中去除VIEWSTATE视图状态乱码

    保存页的所有视图状态信息和控件状态信息. 基于SEO技术的开发,在没有接触MVC框架 Razor 引擎的时候,我们需要使用ASP.NET引擎,如果使用ASP.NET引擎的服务器端控件,那么在ASP.N ...

  3. ASP.NET页面中去除VIEWSTATE视

    保存页的所有视图状态信息和控件状态信息. 源码:http://www.jinhusns.com/Products/Download/?type=xcj 作者在早期参与的项目中曾遇到这样的需求:基于SE ...

  4. Asp.net页面中调用soapheader进行验证的操作步骤

    Asp.net页面中调用以SOAP头作验证的web services操作步骤 第一步:用来作SOAP验证的类必须从SoapHeader类派生,类中Public的属性将出现在自动产生XML节点中,即: ...

  5. Vue 动态控制页面中按钮是否显示和样式

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. vue基于页面中按钮权限控制

    main.js // 权限 /** 权限指令,对按钮权限的控制 **/ Vue.directive('allow', { bind: function(el, binding) { // 通过当前按钮 ...

  7. asp.net 页面上的点击事件

    asp.net 页面上 服务器端控件Button 有两个click事件如 <asp:Button ID="Button1" runat="server" ...

  8. iOS中按钮点击事件处理方式

    写在前面 在iOS开发中,时常会用到按钮,通过按钮的点击来完成界面的跳转等功能.按钮事件的实现方式有多种,其中 较为常用的是目标-动作对模式.但这种方式使得view与controller之间的耦合程度 ...

  9. 如何在ASP.NET页面中使用异步任务(PageAsyncTask)

    在页面加载期间,可能有些操作是要比较耗用时间的(例如调用外部资源,要长时间等待其返回),正常情况下,这个操作将一直占用线程.而大家知道,ASP.NET在服务端线程池中的线程数是有限的,如果一直占用的话 ...

随机推荐

  1. javascript操作html元素CSS属性

    下面先记录一下JS控制CSS所使用的方法. 1.使用javascript更改某个css class的属性... <style type="text/css"> .ori ...

  2. python描述符descriptor(一)

    Python 描述符是一种创建托管属性的方法.每当一个属性被查询时,一个动作就会发生.这个动作默认是get,set或者delete.不过,有时候某个应用可能会有 更多的需求,需要你设计一些更复杂的动作 ...

  3. linux下修改IP信息

    在Linux的系统下如何才能修改IP信息 以前总是用ifconfig修改,重启后总是得重做.如果修改配置文件,就不用那么麻烦了- A.修改ip地址 即时生效: # ifconfig eth0 192. ...

  4. visualvm 监控 远程 机器上的 Java 程序

    JDK里面本身就带了很多的监控工具,如JConsole等. 我们今天要讲的这款工具visualvm,就是其中的一款.但是这款工具是在JDK1.6.07及以上才有的.它能够对JAVA程序的JVM堆.线程 ...

  5. sjtu1333 函数时代

    Description Taring说:生活的过程就是执行函数的过程.需要命令,也需要回报.更重要的,是得到回报的过程. 好吧...这道题其实和上面的也没啥关系TAT,我们要求的是下面的问题: 给定\ ...

  6. 解决win8 plsql无法登录

    今天安装完oracle客户端,然后打开 plsql 之后,就一个提示框,提示没有登录,后来解决方法如下: 在plsql的图标上点右键,以管理员身份运行,即可! 如果不想一直点右键执行,就图标上点右键- ...

  7. java多线程下载和断点续传

    java多线程下载和断点续传,示例代码只实现了多线程,断点只做了介绍.但是实际测试结果不是很理想,不知道是哪里出了问题.所以贴上来请高手修正. [Java]代码 import java.io.File ...

  8. Codeforces Round #236 (Div. 2)

    A. Nuts time limit per test:1 secondmemory limit per test:256 megabytesinput:standard inputoutput:st ...

  9. Linux下打包压缩成war包和解压war包

    一. 打包成war包 因为种种原因公司需要把java程序达成war包.起先用zip命令打包,起先可以用,后来却无法使用.今天找到一个更好的办法.用jar命令,前提是要安装jdk. 把当前目录下的所有文 ...

  10. 在redhat6.4下安装 Oracle® Database 11g Release 2

    OS版本: 安装过程的相关信息: pdksh 安装好后根据需要设置oracle开机自启动http://www.cnblogs.com/softidea/p/3761671.html 设置环境变量NLS ...