利用wininet.dll 組件讀取cookie :
[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);
private static string GetCookies(string url)
{
uint datasize = 1024;
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解析的過程中:
cookie的value中如果包含有,(逗號)的情況下,可用 %2C 替換掉
舉例:
CookieContainer cookieContainer = new CookieContainer();
string cookieStr = GetCookies("http://abc.com/");
string[] cookstr = cookieStr.Split(';');
foreach (string str in cookstr)
{
string[] data= str.Split('=');
if (data[1].Trim().ToString().IndexOf(',') != -1)
{
data[1] = data[1].Trim().ToString().Replace(",", "%2C");
}
Cookie ck = new Cookie(data[0].Trim().ToString(), data[1].Trim().ToString());
cookieContainer .Add(new Uri("http://abc.com/"), ck);
}
end。