There are many pages that cannot be accessed directly, often due to session or cookie control. You need a user name and password to log on before you can see how to use Asp.netProgramDirectly retrieve the page to be verified? The following function can be implemented:
Protected static string cookieheader;
Public String login (string URL, string paramlist)
{
Httpwebresponse res = NULL;
String strresult = "";
Try
{
Httpwebrequest Req = (httpwebrequest) webrequest. Create (URL );
Req. method = "Post ";
Req. contenttype = "application/X-WWW-form-urlencoded ";
Req. allowautoredirect = false;
Cookiecontainer cookiecon = new cookiecontainer ();
Req. cookiecontainer = cookiecon;
Stringbuilder urlencoded = new stringbuilder ();
Char [] reserved = {'? ',' = ','&'};
Byte [] somebytes = NULL;
If (paramlist! = NULL)
{
Int I = 0, J;
While (I < Paramlist . Length)
{
J = Paramlist. indexofany (reserved, I );
If (J =-1)
{
Urlencoded. append (httputility. urlencode (paramlist. substring (I, paramlist. Length-I )));
Break;
}
Urlencoded. append (httputility. urlencode (paramlist. substring (I, j-I )));
Urlencoded. append (paramlist. substring (J, 1 ));
I = J + 1;
}
Somebytes = Encoding. utf8.getbytes (urlencoded. tostring ());
Req. contentlength = Somebytes. length;
Stream newstream = Req. getrequeststream ();
Newstream. Write (somebytes, 0, somebytes. Length );
Newstream. Close ();
}
Else
{
Req. contentlength = 0;
}
Res = (Httpwebresponse) Req. getresponse ();
Cookieheader = Req. cookiecontainer. getcookieheader (New Uri (URL ));
Httpcontext. Current. application. Lock ();
Httpcontext. Current. application ["cookieheader"] = Cookieheader;
Httpcontext. Current. application. Unlock ();
Stream receivestream = Res. getresponsestream ();
Encoding encode = System. Text. encoding. utf8;
Streamreader SR = New Streamreader (receivestream, encode );
Char [] Read = New Char [256];
Int count = Sr. Read ( Read, 0,256 );
While (count > 0)
{
String STR = new string (read, 0, count );
Strresult + = STR;
Count = Sr. Read (read, 0,256 );
}
}
Catch (exception E)
{
Strresult = E. tostring ();
}
Finally
{
If (res! = NULL)
{
Res. Close ();
}
}
Strresult = strresult. Replace ("\ r \ n ","");
Return strresult;
}
Parameter description: URL indicates the submitted target page.
Paramlist indicates the parameter list (Format: param1 = 123 & parma2 = 456)
Example:
Void loginsample ()
{
If (httpcontext. Current. application ["cookieheader"]! = NULL)
{
Cookieheader = (string) httpcontext. Current. application ["cowokieheader"];
}
Else
{
Login ("http://www.myule.com/login.asp", "user = likef & Password = likef & next = login ");
}
When running the above function, a cookie is generated, and the page content to be verified can be easily obtained.