Webbrowser cookie operations
1. Get cookie in webbrowser
Cookiecontainer mycookiecontainer = new cookiecontainer ();
String cookiestr = webbrowser1.document. Cookie;
String [] cookstr = cookiestr. Split (';');
Foreach (string STR in cookstr)
{
String [] cookienamevalue = Str. Split ('= ');
Cookie ck = new cookie (cookienamevalue [0]. Trim (). tostring (), cookienamevalue [1]. Trim (). tostring ());
CK. Domain = "www.google.com ";
Mycookiecontainer. Add (CK );
}
Set cookie in WebClient!
WebClient WC = new WebClient ();
WC. headers. Add ("cookie", "PHPSESSID =" + Cookie + ";");
// Note that the cookie is not set-Cookie.
Byte [] Re = WC. uploaddata (Global. rootpath + "test. php", new byte [0]);
System. Text. utf8encoding converter = new system. Text. utf8encoding ();
String STR = converter. getstring (re );
2. Set cookie in webbrowser
Public partial class webbrowsercontrol: Form
{
Private string URL;
[Dllimport ("wininet. dll", charset = charset. Auto, setlasterror = true)]
Public static extern bool internetsetcookie (string lpszurlname, string lbszcookiename, string lpszcookiedata );
Public webbrowsercontrol (string path)
{
This. url = path;
Initializecomponent ();
// Set cookie
Internetsetcookie (URL, "JSESSIONID", globals. thisdocument. sessionid );
// Navigate
Webbrowser. navigate (URL );
}
}
3. Pass the cookie information of webbrowser to httpwebrequest
Create a "cookiecontainer" to save the cookie in webbrowser
// Log on to the webbrowser and save the cookie in webbrowser. Document. Cookie.
Cookiecontainer mycookiecontainer = new cookiecontainer ();
// String cookie to be converted to cookie type and put into cookiecontainer
String cookiestr = webbrowser1.document. Cookie;
String [] cookstr = cookiestr. Split (';');
foreach (string STR in cookstr)
{< br> string [] cookienamevalue = Str. split ('=');
cookie ck = new cookie (cookienamevalue [0]. trim (). tostring (), cookienamevalue [1]. trim (). tostring ();
CK. domain = "www.abc.com"; // must be written to
mycookiecontainer. add (CK);
}
Httpwebrequest hreq = (httpwebrequest) httpwebrequest. Create ("http://www.abc.com/search.asp ");
Hreq. method = "Post ";
Hreq. contenttype = "application/X-WWW-form-urlencoded ";
// Cookiecontainer created by yourself
Hreq. cookiecontainer = mycookiecontainer;
String postdata = "id = 2005 & Action = SEARCH & name = ";
Byte [] byte1 = encoding. ASCII. getbytes (postdata );
Hreq. contentlength = byte1.length;
Stream poststream = hreq. getrequeststream ();
Poststream. Write (byte1, 0, byte1.length );
Poststream. Close ();
Httpwebresponse hres = (httpwebresponse) hreq. getresponse ();