您的位置:首页 > 其它

Document.Cookie 取得的Cookies不完整問題

2012-02-20 01:12 218 查看
http://mobile.dotblogs.com.tw/jgame2012/archive/2011/12/22/63176.aspx

http://www.dotblogs.com.tw/jgame2012/archive/2011/12/22/63176.aspx

/article/11676960.html

获取完整COOKIES:

有時候需要取得WebBrowser所在的頁面的Cookie,就會像下面這樣寫

string cookie = webBrowser1.Document.Cookie;


但取得的Cookie屬性內容並非為真正請求出去所包含的所有Cookie,若要取得實際請求會送出的網址Cookie,就可以使用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);


InternetSetCookieEx是設定Cookie,在這裡的範例不會使用到,而InternetGetCookieEx使用方式可以參閱這裡,主要是取得IE瀏覽器的Cookie,以下的靜態方法是可以輸入網址後,取得該網址所包含的Cookies

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();
}

註:GetCookies靜態方法的代碼是修改網路上不知名版本,然後在對應上述所宣告的API參數所改寫。

设置COOKIES:

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);


1、设置Cookie

InternetSetCookie(
"https://" + cookie.Domain.ToString(),
cookie.Name.ToString(),
cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");


2、删除Cookie

InternetSetCookie(url,NULL,L"CookieTest=ValTest;path=path value;expires=Thu, 01-Jan-1970 00:00:01 GMT");


使用InternetSetCookie删除cookie ms没有官方文档。经过无数次的测试之后发现:

1。 删除时一定要传入path参数,而且此参数必须和set是一致.
2。 setcookie是不带path参数则是对当前path起作用(如果url是一个文件的话,MS有问题)
3。 不同path值,即使cookie的名字一样也是两个不同的cookie。所以path很重要啊!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: