在没有做题目中所述的内容的时候,感觉这应该是很简单的东西,但是当真正开始做的时候却发现,有很多问题
现在在这里写出来,供和我一样水平不高的参考一下。
在写本文之前参照了一下文章
欢迎使用CSDN论坛阅读器 : CSDN Reader(附全部源代码) 最新版本:20070212
http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
C#通过webRequest保持在同一Session中Post数据 http://blog.csdn.net/crabo/archive/2005/12/08/547092.aspx
c# 模拟Asp.net页面中的某个按钮的点击,向web服务器发出请求
主要就组织要提交的数据,然后以post方式提交。
假设我们有如下的网页

1 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ 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">
<!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" >
<html xmlns="http://www.w3.org/1999/xhtml" >
6 <head runat="server">
<head runat="server">
7 <title>无标题页</title>
    <title>无标题页</title>
8 </head>
</head>
9 <body>
<body>
10 <form id="form1" runat="server">
    <form id="form1" runat="server">
11 <div>
    <div>
12 <table>
       <table>
13 <tr>
       <tr>
14 <td> 姓名:</td><td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
        <td> 姓名:</td><td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
15 </tr>
       </tr>
16 <tr>
              <tr>
17 <td> 昵称:</td><td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password" Width="149px"></asp:TextBox></td>
        <td> 昵称:</td><td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password" Width="149px"></asp:TextBox></td>
18 </tr>
       </tr>
19 </table>
       </table>
20 <asp:Button ID="btnUpdate" runat="server" Text="Longon" OnClick="btnUpdate_Click" Width="60px" />
        <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 />
        <asp:Button ID="btnClose" runat="server" OnClick="btnClose_Click" Text="Close" /><br />
22 
    
23 </div>
    </div>
24 </form>
    </form>
25 </body>
</body>
26 </html>用IE访问这个页面的时候可以得到如下的输出
</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">
<!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" >
<html xmlns="http://www.w3.org/1999/xhtml" >
6 <head><title>
<head><title>
7 无标题页
    无标题页
8 </title></head>
</title></head>
9 <body>
<body>
10 <form name="form1" method="post" action="Default.aspx" id="form1">
    <form name="form1" method="post" action="Default.aspx" id="form1">
11 <div>
<div>
12 <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=" />
13 </div>
</div>
14
15 <div>
    <div>
16 <table>
       <table>
17 <tr>
       <tr>
18 <td> 姓名:</td><td><input name="txtName" type="text" id="txtName" /></td>
        <td> 姓名:</td><td><input name="txtName" type="text" id="txtName" /></td>
19 </tr>
       </tr>
20 <tr>
              <tr>
21 <td> 昵称:</td><td><input name="txtPwd" type="password" id="txtPwd" style="width:149px;" /></td>
        <td> 昵称:</td><td><input name="txtPwd" type="password" id="txtPwd" style="width:149px;" /></td>
22 </tr>
       </tr>
23 </table>
       </table>
24 <input type="submit" name="btnUpdate" value="Logon" id="btnUpdate" style="width:60px;" />
        <input type="submit" name="btnUpdate" value="Logon" id="btnUpdate" style="width:60px;" />
25 <input type="submit" name="btnClose" value="Close" id="btnClose" /><br />
        <input type="submit" name="btnClose" value="Close" id="btnClose" /><br />
26 
    
27 </div>
    </div>
28 
    
29 <div>
<div>
30
31 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ" />
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ" />
32 </div></form>
</div></form>
33 </body>
</body>
34 </html>
</html>
35
由上面的代码可以看出除了txtName,txtPwd以及两个按钮外,多出了两个__VIEWSTATE,__EVENTVALIDATION这四个表单需要提交到的,要模拟哪个按钮,在加上哪个按钮的表单的值就可以了,如:btnUpdate=Logon
在拼接提交的字符串的时候注意一下,用System.Web.HttpUtility.UrlEncode方法转换成Url编码的字符串。
下面是针对这个页面的btnUpdate按钮的提交数据
然后创建一个HttpWebRequest对象,设置提交方式是post,然后把上面准备的字符串写进请求数据流里
基本上就可以了
如果有需要在访问不同页面时保存Session的话,需要设置HttpWebRequest对象的CookieContainer属性,保证每次设置的CookieContainer都是同一个对象就可以了。
下面是这个类就是向WEB页面发出请求,并得到返回数据的类

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

1 private WebPageReader webReader = new WebPageReader();
private WebPageReader webReader = new WebPageReader();
2
3 string __VIEWSTATE = "/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=";
string __VIEWSTATE = "/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=";
4 string __EVENTVALIDATION = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ";
string __EVENTVALIDATION = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ";
5
6 __VIEWSTATE = System.Web.HttpUtility.UrlEncode(__VIEWSTATE);
__VIEWSTATE = System.Web.HttpUtility.UrlEncode(__VIEWSTATE);
7
8 __EVENTVALIDATION = System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);
__EVENTVALIDATION = System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);
9
10 string strPostData = String.Format("__VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3}"
string strPostData = String.Format("__VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3}"
11 , __VIEWSTATE, this.txtName.Text, this.txtPassword.Text, __EVENTVALIDATION
                            , __VIEWSTATE, this.txtName.Text, this.txtPassword.Text, __EVENTVALIDATION
12 );
                            );
13 string strHTML;
string strHTML;
14
15 try
try
16 {
{
17 do
    do
18 {
    {
19 strHTML = webReader.GetHTML("http://localhost:3517/WebSite1/Default.aspx", strPostData);
        strHTML = webReader.GetHTML("http://localhost:3517/WebSite1/Default.aspx", strPostData);
20 } while (webReader.IsKeepAlive);
    } while (webReader.IsKeepAlive);
21
22
23 this.richTextBox1.Text = strHTML;
    this.richTextBox1.Text = strHTML;
24 }
}
25 catch (Exception ex)
catch (Exception ex)
26 {
{
27 if (ex.InnerException != null)
    if (ex.InnerException != null)
28 {
    {
29 MessageBox.Show(ex.Message + "\n" + ex.InnerException.Message);
        MessageBox.Show(ex.Message + "\n" + ex.InnerException.Message);
30 }
    }
31 else
    else
32 {
    {
33 MessageBox.Show(ex.Message);
        MessageBox.Show(ex.Message);
34 }
    }
35 }
}
现在在这里写出来,供和我一样水平不高的参考一下。
在写本文之前参照了一下文章
欢迎使用CSDN论坛阅读器 : CSDN Reader(附全部源代码) 最新版本:20070212
http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
C#通过webRequest保持在同一Session中Post数据 http://blog.csdn.net/crabo/archive/2005/12/08/547092.aspx
c# 模拟Asp.net页面中的某个按钮的点击,向web服务器发出请求
主要就组织要提交的数据,然后以post方式提交。
假设我们有如下的网页

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

2

3
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!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" >
<html xmlns="http://www.w3.org/1999/xhtml" >6
 <head><title>
<head><title>7
 无标题页
    无标题页8
 </title></head>
</title></head>9
 <body>
<body>10
 <form name="form1" method="post" action="Default.aspx" id="form1">
    <form name="form1" method="post" action="Default.aspx" id="form1">11
 <div>
<div>12
 <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=" />13
 </div>
</div>14

15
 <div>
    <div>16
 <table>
       <table>17
 <tr>
       <tr>18
 <td> 姓名:</td><td><input name="txtName" type="text" id="txtName" /></td>
        <td> 姓名:</td><td><input name="txtName" type="text" id="txtName" /></td>19
 </tr>
       </tr>20
 <tr>
              <tr>21
 <td> 昵称:</td><td><input name="txtPwd" type="password" id="txtPwd" style="width:149px;" /></td>
        <td> 昵称:</td><td><input name="txtPwd" type="password" id="txtPwd" style="width:149px;" /></td>22
 </tr>
       </tr>23
 </table>
       </table>24
 <input type="submit" name="btnUpdate" value="Logon" id="btnUpdate" style="width:60px;" />
        <input type="submit" name="btnUpdate" value="Logon" id="btnUpdate" style="width:60px;" />25
 <input type="submit" name="btnClose" value="Close" id="btnClose" /><br />
        <input type="submit" name="btnClose" value="Close" id="btnClose" /><br />26
 
    27
 </div>
    </div>28
 
    29
 <div>
<div>30

31
 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ" />
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ" />32
 </div></form>
</div></form>33
 </body>
</body>34
 </html>
</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 );
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;
using System;2
 using System.Net;
using System.Net;3

4
 namespace Dlse.Com.Cn.Why
namespace Dlse.Com.Cn.Why5
 {
{6
 class WebPageReader
    class WebPageReader7
 {
    {8

9
 /// <summary>
        /// <summary>10
 /// cookie
        /// cookie11
 /// </summary>
        /// </summary>12
 private CookieCollection _Cookies = new CookieCollection();
        private CookieCollection _Cookies = new CookieCollection();13

14
 /// <summary>
        /// <summary>15
 /// 保持提交到同一个Session
        /// 保持提交到同一个Session16
 /// </summary>
        /// </summary>17
 private CookieContainer cookieContainer = new CookieContainer();
        private CookieContainer cookieContainer = new CookieContainer();18

19
 /// <summary>
        /// <summary>20
 /// 保持连接
        /// 保持连接21
 /// </summary>
        /// </summary>22
 private bool isKeepAlive = false;
        private bool isKeepAlive = false;23

24
 public bool IsKeepAlive
        public bool IsKeepAlive25
 {
        {26
 get { return isKeepAlive; }
            get { return isKeepAlive; }27
 set { isKeepAlive = value; }
            set { isKeepAlive = value; }28
 }
        }29
 
        30

31

32
 public string GetHTML(string URL)
        public string GetHTML(string URL)33
 {
        {34
 return GetHTML(URL, "", System.Text.Encoding.ASCII);
            return GetHTML(URL, "", System.Text.Encoding.ASCII);35
 }
        }36

37
 public string GetHTML(string URL, string PostData)
        public string GetHTML(string URL, string PostData)38
 {
        {39
 return GetHTML(URL, PostData, System.Text.Encoding.ASCII);
            return GetHTML(URL, PostData, System.Text.Encoding.ASCII);40
 }
        }41

42
 public string GetHTML(string URL, System.Text.Encoding encoding)
        public string GetHTML(string URL, System.Text.Encoding encoding)43
 {
        {44
 return GetHTML(URL,"",encoding );
            return GetHTML(URL,"",encoding );45
 }
        }46

47
 /// <summary>
        /// <summary>48
 /// 获取指定地址的html
        /// 获取指定地址的html49
 /// </summary>
        /// </summary>50
 /// <param name="URL"></param>
        /// <param name="URL"></param>51
 /// <param name="PostData"></param>
        /// <param name="PostData"></param>52
 /// <param name="encoding"></param>
        /// <param name="encoding"></param>53
 /// <returns></returns>
        /// <returns></returns>54
 public string GetHTML(string URL, string PostData, System.Text.Encoding encoding)
        public string GetHTML(string URL, string PostData, System.Text.Encoding encoding)55
 {
        {56
 isKeepAlive = false;
            isKeepAlive = false;57
 string _Html = "";
            string _Html = "";58

59
 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            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, */*";
            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)
            if (_Cookies.Count > 0)64
 {
            {65
 request.CookieContainer.Add(new Uri(URL), _Cookies);
                request.CookieContainer.Add(new Uri(URL), _Cookies);66
 }
            }67
 else
            else68
 {
            {69
 request.CookieContainer = this.cookieContainer;
                request.CookieContainer = this.cookieContainer;70
 }
            }71

72
 //提交的数据
            //提交的数据73
 if (PostData != null && PostData.Length > 0)
            if (PostData != null && PostData.Length > 0)74
 {
            {75
 request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType = "application/x-www-form-urlencoded";76
 request.Method = "POST";
                request.Method = "POST";77

78
 byte[] b = encoding.GetBytes(PostData);
                byte[] b = encoding.GetBytes(PostData);79
 request.ContentLength = b.Length;
                request.ContentLength = b.Length;80
 using (System.IO.Stream sw = request.GetRequestStream())
                using (System.IO.Stream sw = request.GetRequestStream())81
 {
                {82
 try
                    try83
 {
                    {84
 sw.Write(b, 0, b.Length);
                        sw.Write(b, 0, b.Length);85
 }
                    }86
 catch (Exception ex)
                    catch (Exception ex)87
 {
                    {88
 throw new Exception("Post Data Error!!", ex);
                        throw new Exception("Post Data Error!!", ex);89
 }
                    }90
 finally
                    finally91
 {
                    {92
 if (sw != null) { sw.Close(); }
                        if (sw != null) { sw.Close(); }93
 }
                    }94
 }
                }95
 }
            }96

97

98
 HttpWebResponse response = null;
            HttpWebResponse response = null;99
 System.IO.StreamReader sr = null;
            System.IO.StreamReader sr = null;100

101
 try
            try102
 {
            {103

104
 response = (HttpWebResponse)request.GetResponse();
                response = (HttpWebResponse)request.GetResponse();105
 
            106
 _Cookies = response.Cookies;
                _Cookies = response.Cookies;107

108
 sr = new System.IO.StreamReader(response.GetResponseStream(), encoding);
                sr = new System.IO.StreamReader(response.GetResponseStream(), encoding);109

110
 _Html = sr.ReadToEnd();
                _Html = sr.ReadToEnd();111

112
 }
            }113
 catch (WebException webex)
            catch (WebException webex)114
 {
            {115
 if (webex.Status == WebExceptionStatus.KeepAliveFailure)
                if (webex.Status == WebExceptionStatus.KeepAliveFailure)116
 {
                {117
 isKeepAlive = true;
                    isKeepAlive = true;118
 }
                }119
 else
                else120
 {
                {121
 throw new Exception("DownLoad Data Error", webex);
                    throw new Exception("DownLoad Data Error", webex);122
 }
                }123
 }
            }124
 catch (System.Exception ex)
            catch (System.Exception ex)125
 {
            {126
 throw new Exception("DownLoad Data Error", ex);
                throw new Exception("DownLoad Data Error", ex);127
 }
            }128
 finally
            finally129
 {
            {130
 if (sr != null) { sr.Close(); }
                if (sr != null) { sr.Close(); }131
 if (response != null) { response.Close(); }
                if (response != null) { response.Close(); }132
 response = null;
                response = null;133
 request = null;
                request = null;134
 }
            }135

136
 return _Html;
            return _Html;137

138
 }
        }139
 }
    }140
 }
}141

使用方法如下

1
 private WebPageReader webReader = new WebPageReader();
private WebPageReader webReader = new WebPageReader();2

3
 string __VIEWSTATE = "/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=";
string __VIEWSTATE = "/wEPDwUKMTg4ODA4NDE0NmRk6Ma0MaCJKrrNLGLfO4qYNezoxY4=";4
 string __EVENTVALIDATION = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ";
string __EVENTVALIDATION = "/wEWBQKcopufDgLEhISFCwKd+7qdDgLynailDAKT+PmaCJleqITXMfQuE9LK49YoxHV2oTzQ";5

6
 __VIEWSTATE = System.Web.HttpUtility.UrlEncode(__VIEWSTATE);
__VIEWSTATE = System.Web.HttpUtility.UrlEncode(__VIEWSTATE);7

8
 __EVENTVALIDATION = System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);
__EVENTVALIDATION = System.Web.HttpUtility.UrlEncode(__EVENTVALIDATION);9

10
 string strPostData = String.Format("__VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3}"
string strPostData = String.Format("__VIEWSTATE={0}&txtName={1}&txtPwd={2}&btnUpdate=Longon&__EVENTVALIDATION={3}"11
 , __VIEWSTATE, this.txtName.Text, this.txtPassword.Text, __EVENTVALIDATION
                            , __VIEWSTATE, this.txtName.Text, this.txtPassword.Text, __EVENTVALIDATION12
 );
                            );13
 string strHTML;
string strHTML;14

15
 try
try16
 {
{17
 do
    do18
 {
    {19
 strHTML = webReader.GetHTML("http://localhost:3517/WebSite1/Default.aspx", strPostData);
        strHTML = webReader.GetHTML("http://localhost:3517/WebSite1/Default.aspx", strPostData);20
 } while (webReader.IsKeepAlive);
    } while (webReader.IsKeepAlive);21

22

23
 this.richTextBox1.Text = strHTML;
    this.richTextBox1.Text = strHTML;24
 }
}25
 catch (Exception ex)
catch (Exception ex)26
 {
{27
 if (ex.InnerException != null)
    if (ex.InnerException != null)28
 {
    {29
 MessageBox.Show(ex.Message + "\n" + ex.InnerException.Message);
        MessageBox.Show(ex.Message + "\n" + ex.InnerException.Message);30
 }
    }31
 else
    else32
 {
    {33
 MessageBox.Show(ex.Message);
        MessageBox.Show(ex.Message);34
 }
    }35
 }
} 
                    
                

 
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号