1、WebBrowser设置Cookie
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1public partial class WebBrowserControl : Form
2 {
3 private String url;
4
5 [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
6 public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
7
8 public WebBrowserControl(String path)
9 {
this.url = path;
InitializeComponent();
// set cookie
InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID);
// navigate
webBrowser.Navigate(url);
}
}
2、将WebBrowser的cookie信息传给HttpWebRequest.
先建一个"CookieContainer" 把WebBrowser中的Cookie保存在里面
//在WebBrowser中登录 cookie保存在 WebBrowser.Document.Cookie中
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 CookieContainer myCookieContainer = new CookieContainer();
2
3
4 //String 的Cookie 要转成 Cookie型的 并放入CookieContainer中
5 string cookieStr = webBrowser1.Document.Cookie;
6 string[] cookstr = cookieStr.Split(';');
7 foreach (string str in cookstr)
8 {
9 string[] cookieNameValue = str.Split('=');
].Trim().ToString());
ck.Domain = "www.abc.com";//必须写对
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
hreq.CookieContainer = myCookieContainer;
string postdata = "id=2005&action=search&name=";
byte[] byte1 = Encoding.ASCII.GetBytes(postdata);
hreq.ContentLength = byte1.Length;
Stream poststream = hreq.GetRequestStream();
, byte1.Length);
poststream.Close();
HttpWebResponse hres = (HttpWebResponse)hreq.GetResponse();