paip.C#.NET利用WebBrowser获取完整COOKIE
使用WebBrowser获取一个网站的COOKIE,在调用Document.Cookie时,发现无法完整获取其COOKIe..
1.原因:
----------
此 Cookie,加入了.httponly
2.解决方法1: 使用WIN API获取
---------------------------------
就可以使用InternetGetCookieEx這個Win API來取得,下面是API的方法宣告
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref
System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int InternetSetCookieEx(string lpszURL, string lpszCookieName, string lpszCookieData, int dwFlags,
IntPtr dwReserved);
private static string GetCookies(string url)
{
uint datasize = 256;
StringBuilder cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
{
if (datasize < 0)
return null;
cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
return null;
}
return cookieData.ToString();
}
实际上它是通过本地COOKIE文件的读取,来取得COOIE的..
3.解决方法2:自已写方法读取本地COOKIE文件
-------------------
public string Cookie()
2 { www.2cto.com
3 if (this.Url == null)
4 return null;
5 string dir = this.Url.Host;
6 FileStream fr = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\
\index.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
************
代码比较长,省略..