WebBrowser Cookie Operation 1. Obtaining Cookies 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); } WebClient setting cookie! WebClient WC = new WebClient (); Wc. Headers.add ("Cookie", "phpsessid=" + cookie + ";"); Note that this is a Cookie, not a 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. Setting a 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 WebBrowser cookie information to HttpWebRequest Build a "cookiecontainer" to keep the cookies in the WebBrowser. Login cookie in WebBrowser saved in WebBrowser.Document.Cookie Cookiecontainer Mycookiecontainer = new Cookiecontainer (); The cookie of String is to be converted into a cookie type and put into 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.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";
Self-created Cookiecontainer 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 (); |