Use httpwebrequest to submit ASP. NET forms and keep session and cookie

Source: Internet
Author: User

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. AllSource code: Autopostwithcookies.rar

Three pages are involved: mylogin.aspx,loginok.htm, default. aspx:
1) mylogin. ASPX page

The mylogin. ASPX page is the logon page. If the user name and password are correct, the session and cookie (loginsession and logincookie) are generated and then directed to the loginok.htm page.

2)loginok.htm page

The loginok.htm page is a jump page. After a few seconds, it will automatically jump to the default. aspx page.

3) default. aspx page

The default. aspx page is the main interface. When the main interface is opened, the system checks whether the values of loginsession and logincookie are correct and displays the values of session and cookie.

Submit the ASP. NET form (that is, complete automatic login)CodeAs follows:

Try
{
Cookiecontainer = new cookiecontainer ();

//////////////////////////////////////// ///////////
// 1. Open the mylogin. ASPX page and obtain veiwstate & eventvalidation.
//////////////////////////////////////// ///////////
// Set parameters for opening the page
String Uri =   " Http: // localhost: 1165/webtest/mylogin. aspx " ;
Httpwebrequest request = Webrequest. Create (URI) As Httpwebrequest;
Request. Method =   " Get " ;
Request. keepalive =   False ;

// Receive returned page
Httpwebresponse response = Request. getresponse () As Httpwebresponse;
System. Io. Stream responsestream = Response. getresponsestream ();
System. Io. streamreader Reader =   New System. Io. streamreader (responsestream, encoding. utf8 );
String Srcstring = Reader. readtoend ();

// Obtain the veiwstate of the page
String Viewstateflag =   " Id = \ " _ Viewstate \ " Value = \ "" ;
Int I = Srcstring. indexof (viewstateflag) + Viewstateflag. length;
Int J = Srcstring. indexof ( " \ "" , I );
String Viewstate = Srcstring. substring (I, j - I );

// Get eventvalidation of the page
String Eventvalidationflag =   " Id = \ " _ Eventvalidation \ " Value = \ "" ;
I = Srcstring. indexof (eventvalidationflag) + Eventvalidationflag. length;
J = Srcstring. indexof ( " \ "" , I );
String Eventvalidation = Srcstring. substring (I, j - I );

//////////////////////////////////////// ///////////
// 2. Automatically fill and submit the mylogin. ASPX page
//////////////////////////////////////// ///////////
// Text of the submit button
String Submitbutton =   " Login " ;

// user name and password
string username = " 1 " ;
string password = " 1 " ;

//Convert text into URL encoded strings
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
String Formatstring =  
" Username = {0} & Password = {1} & loginbutton = {2} & __ viewstate = {3} & __ eventvalidation = {4} " ;
String Poststring =  
String . Format (formatstring, username, password, submitbutton, viewstate, eventvalidation );

//Converts the submitted string data to a byte array.
Byte[] Postdata=Encoding. ASCII. getbytes (poststring );

// Set parameters for submission
Request = Webrequest. Create (URI) As Httpwebrequest;
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. Stream outputstream=Request. getrequeststream ();
Outputstream. Write (postdata,0, Postdata. Length );
Outputstream. Close ();

// Receive returned page
Response = Request. getresponse () As Httpwebresponse;
Responsestream = Response. getresponsestream ();
Reader =   New System. 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) As Httpwebrequest;
Request. Method =   " Get " ;
Request. keepalive =   False ;
Request. cookiecontainer = cookiecontainer;

// Receive returned page
Response = Request. getresponse () As Httpwebresponse;
Responsestream = Response. getresponsestream ();
Reader =   New System. Io. streamreader (responsestream, encoding. utf8 );
Srcstring = Reader. readtoend ();

//////////////////////////////////////// ///////////
// 4. Analyze the returned page
//////////////////////////////////////// ///////////
//
}
Catch (Webexception we)
{
String MSG = 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.

All source code in this article: autopostwithcookies.rar

RelatedArticle: Use WebClient to automatically fill in and submit ASP. NET page forms
Use WebClient to automatically enter and submit the source code of the ASP. NET page form
Use regular expressions in C # To automatically match and obtain the required data.

Address: http://www.cnblogs.com/anjou/archive/2007/10/15/923770.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.