Use HttpWebRequest to submit ASP. NET forms and keep Session and Cookie
For various reasons, we sometimes need to capture some information from the Internet, some pages can be opened directly, and some pages can be opened only after login. This document describes a complete example of using HttpWebRequest and HttpWebResponse to automatically submit ASP. NET forms and maintain Session and Cookie. All source code in this article: AutoPostWithCookies.rar
Three pages are involved: MyLogin.aspx,LoginOK.htm, Default. aspx:
1) MyLogin. aspx page
2)LoginOK.htm page
3) Default. aspx page
The following code submits an ASP. NET form to complete automatic logon:
- Try
- {
- CookieContainercookieContainer=NewCookieContainer();
-
- //////////////////////////////////////// ///////////
- // 1. Open the MyLogin. aspx page and obtain VeiwState & EventValidation
- //////////////////////////////////////// ///////////
- // Set parameters for opening the page
- StringURI="Http: // localhost: 1165/WebTest/MyLogin. aspx";
- HttpWebRequestrequest= WebRequest. Create (URI) asHttpWebRequest;
- Request. Method="GET";
- Request. KeepAlive=False;
-
- // Receive the returned page
- HttpWebResponseresponse=Request. GetResponse () asHttpWebResponse;
- System. IO. StreamresponseStream= Response. GetResponseStream ();
- System. IO. StreamReaderreader=NewSystem. IO. StreamReader (responseStream, Encoding. UTF8 );
- StringsrcString=Reader. ReadToEnd ();
-
- // Obtain the VeiwState of the page
- StringviewStateFlag= "Id = \"_ VIEWSTATE\"Value= \"";
- Inti=SrcString. IndexOf (viewStateFlag) + viewStateFlag. Length;
- Intj=SrcString. IndexOf ("\" ", I );
- StringviewState=SrcString. Substring (I, j-I );
-
- // Obtain EventValidation of the page
- StringeventValidationFlag= "Id = \"_ EVENTVALIDATION\"Value= \"";
- I=SrcString. IndexOf (eventValidationFlag) + eventValidationFlag. Length;
- J=SrcString. IndexOf ("\" ", I );
- StringeventValidation=SrcString. Substring (I, j-I );
-
- //////////////////////////////////////// ///////////
- // 2. Automatically fill and submit the MyLogin. aspx page
- //////////////////////////////////////// ///////////
- // Text of the submit button
- StringsubmitButton="Login";
-
- // User name and password
- StringuserName="1";
- Stringpassword="1";
-
- // Convert the text into a URL encoded string
- ViewState=System. Web. HttpUtility. UrlEncode (viewState );
- EventValidation=System. Web. HttpUtility. UrlEncode (eventValidation );
- SubmitButton=System. Web. HttpUtility. UrlEncode (submitButton );
-
- // String data to be submitted. Format: User=Uesr1&Password=123
- StringformatString=
- "UserName = {0} & password = {1} & loginButton = {2} & __ VIEWSTATE = {3} & __ EVENTVALIDATION = {4 }";
- StringStringpostString=
- String. Format (formatString, userName, password, submitButton, viewState, eventValidation );
-
- // Convert the submitted string data to a byte array
- Byte []PostData=Encoding. ASCII. GetBytes (postString );
-
- // Set parameters for submission
- Request=WebRequest. Create (URI) asHttpWebRequest;
- Request. Method="POST";
- Request. KeepAlive=False;
- Request. ContentType="Application/x-www-form-urlencoded";
- Request. CookieContainer=CookieContainer;
- Request. ContentLength=PostData. Length;
-
- // Submit request data
- System. IO. StreamoutputStream=Request. GetRequestStream ();
- OutputStream. Write (postData, 0, postData. Length );
- OutputStream. Close ();
-
- // Receive the returned page
- Response=Request. GetResponse () asHttpWebResponse;
- ResponseResponseStream= Response. GetResponseStream ();
- Reader=NewSystem. IO. StreamReader (responseStream, Encoding. GetEncoding ("GB2312 "));
- SrcString=Reader. ReadToEnd ();
-
- //////////////////////////////////////// ///////////
- // 3. Open the Default. aspx page
- //////////////////////////////////////// ///////////
- // Set parameters for opening the page
- URI="Http: // localhost: 1165/WebTest/Default. aspx";
- Request=WebRequest. Create (URI) asHttpWebRequest;
- Request. Method="GET";
- Request. KeepAlive=False;
- Request. CookieContainer=CookieContainer;
-
- // Receive the returned page
- Response=Request. GetResponse () asHttpWebResponse;
- ResponseResponseStream= Response. GetResponseStream ();
- Reader=NewSystem. IO. StreamReader (responseStream, Encoding. UTF8 );
- SrcString=Reader. ReadToEnd ();
-
- //////////////////////////////////////// ///////////
- // 4. Analyze the returned page
- //////////////////////////////////////// ///////////
- //
- }
- Catch (WebExceptionwe)
- {
- Stringmsg=We. Message;
- }
Note:
1) The Cookie container CookieContainer is used to maintain the Session and Cookie. For details, see the red code section.
2) When you POST an ASP. NET page, you need to POST the VeiwState and EventValidation data together. The above introduces ASP. NET forms and maintains Session and Cookie
- Analysis of Theme functions in ASP. NET development skills
- ASP. NET Dynamic Compilation
- Analysis on ASP. NET supported by Apache
- Introduction to ASP. NET Server standard controls
- Analysis on SQL Server Database Backup Recovery in ASP. NET