.将WebBrowser的cookie信息传给HttpWebRequest
第一种方法:
先建一个"CookieContainer" 把WebBrowser中的Cookie保存在里面
//在WebBrowser中登录cookie保存在WebBrowser.Document.Cookie中
CookieContainer myCookieContainer = new CookieContainer();
//String 的Cookie 要转成 Cookie型的 并放入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 = "必须写对
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();
poststream.Write(byte1, 0, byte1.Length);
poststream.Close();
HttpWebResponse hres = (HttpWebResponse)hreq.GetResponse();
第二种方法:
//获取webBrowser的方法,不需要引用其他内裤
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);
private static string GetCookieString(string url)
{
// Determine the size of the cookie
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
return null;
}
return cookieData.ToString();
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers.Clear();
request.Headers[HttpRequestHeader.Cookie] = GetCookieString(url);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.Proxy = null;
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
using (System.IO.Stream dataStream = httpResponse.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(dataStream, Encoding.UTF8))
{
string html = sr.ReadToEnd();
sr.Close();
}
}
httpResponse.Close();
特别说明一下:
CookieContainer cookieCon = new CookieContainer();
req.CookieContainer = cookieCon;
登录后会自动写入COOKIE到CookieContainer中,不需要手工设置cookie的