管理 Cookie

在 http 协议下,服务器或脚本使用 Cookie 来维护客户端工作站上的状态信息。 WinINet 函数已实现永久性 Cookie 数据库以实现此目的。 它们可用于在 中设置 Cookie 并从 Cookie 数据库访问 Cookie。 有关详细信息,请参阅 HTTP Cookie。

InternetSetCookie 和 InternetGetCookie 函数可用于管理 Cookie。

以下函数允许应用程序在 Cookie 数据库中创建或检索 Cookie。

函数 说明
InternetGetCookie 检索指定 URL 及其所有父 URL 的 Cookie。
InternetSetCookie 在指定的 URL 上设置 Cookie。

 

请注意,这些函数不需要调用 InternetOpen。 具有到期日期的 Cookie 存储在 Users\“username”\AppData\Roaming\Microsoft\Windows\Cookies 目录下的本地用户帐户中,以及 Users\“username”\AppData\Roaming\Microsoft\Windows\Cookies\Low 目录(适用于以低特权运行的应用程序)。 没有到期日期的 Cookie 存储在内存中,并且仅适用于创建它们的进程。

如 HTTP Cookie 主题 中所述, InternetGetCookie 函数不会返回已由服务器标记为不可编写脚本的 cookie,Set-Cookie 标头中的“HttpOnly”属性。

InternetGetCookie 返回指定 URL 及其所有父 URL 的 Cookie。

以下示例演示了对 InternetGetCookie 的调用。

TCHAR szURL[256];         // buffer to hold the URL
LPTSTR lpszData = NULL;   // buffer to hold the cookie data
DWORD dwSize=0;           // variable to get the buffer size needed

// Insert code to retrieve the URL.

retry:

// The first call to InternetGetCookie will get the required
// buffer size needed to download the cookie data.
if (!InternetGetCookie(szURL, NULL, lpszData, &dwSize))
{
    // Check for an insufficient buffer error.
    if (GetLastError()== ERROR_INSUFFICIENT_BUFFER)
    {
        // Allocate the necessary buffer.
        lpszData = new TCHAR[dwSize];

        // Try the call again.
        goto retry;
    }
    else
    {
        // Insert error handling code.
    }
}
else
{
    // Insert code to display the cookie data.

    // Release the memory allocated for the buffer.
    delete[]lpszData;
}

InternetSetCookie 用于在指定的 URL 上设置 Cookie。 InternetSetCookie 可以创建持久性 Cookie 和会话 Cookie。

永久性 Cookie 具有到期日期。 这些 Cookie 存储在 Users\“username”\AppData\Roaming\Microsoft\Windows\Cookies 目录下的本地用户帐户中,以及 Users\“username”\AppData\Roaming\Microsoft\Windows\Cookies\Low 目录(适用于以低特权运行的应用程序)。

会话 Cookie 存储在内存中,只能由创建它们的进程访问。

Cookie 的数据应采用以下格式:

NAME=VALUE

对于到期日期,格式必须为:

DAY, DD-MMM-YYYY HH:MM:SS GMT

DAY 是星期日期的三个字母缩写,DD 是月份的日期,MMM 是月份的三个字母缩写,YYYY 是年份,HH:MM:SS 是军事时间中的一天的时间。

以下示例演示对 InternetSetCookie 的两次调用。 第一个调用创建会话 Cookie,第二个调用创建持久性 Cookie。

BOOL bReturn;

// Create a session cookie.
bReturn = InternetSetCookie(TEXT("https://www.adventure_works.com"), NULL,
            TEXT("TestData = Test"));

// Create a persistent cookie.
bReturn = InternetSetCookie(TEXT("https://www.adventure_works.com"), NULL,
           TEXT("TestData = Test; expires = Sat,01-Jan-2000 00:00:00 GMT"));

注意

WinINet 不支持服务器实现。 此外,不应从服务使用它。 对于服务器实现或服务,请使用 Microsoft Windows HTTP Services (WinHTTP) 。