共用方式為


管理 Cookie

在 HTTP 通訊協定下,伺服器或腳本會使用 Cookie 來維護用戶端工作站上的狀態資訊。 WinINet 函式已針對此目的實作持續性 Cookie 資料庫。 它們可用來在 中設定 Cookie,並從 Cookie 數據庫存取 Cookie。 如需詳細資訊,請參閱 HTTP Cookie

InternetSetCookieInternetGetCookie 函式可用來管理 Cookie。

下列函式可讓應用程式在 Cookie 資料庫中建立或擷取 Cookie。

功能 描述
InternetGetCookie 擷取指定 URL 及其所有上層 URL 的 Cookie。
InternetSetCookie 在指定的 URL 上設定 Cookie。

 

請注意,這些函式不需要呼叫 InternetOpen。 到期日的 Cookie 會儲存在使用者\“用戶名稱”\AppData\Roaming\Microsoft\Windows\Cookies 目錄下的本機用戶帳戶中,以及以低許可權執行之應用程式的 Users\“username”\AppData\Roaming\Microsoft\Windows\Cookies\Low 目錄。 沒有到期日的 Cookie 會儲存在記憶體中,而且只能供建立的處理程式使用。

HTTP Cookies 主題所述,InternetGetCookie 函式不會傳回伺服器在 Set-Cookie 標頭中以 “HttpOnly” 屬性標示為不可編寫腳本的 cookies。

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 會儲存在本機使用者帳戶的使用者\“username”\AppData\Roaming\Microsoft\Windows\Cookies 目錄下,而以低權限執行的應用程式則放在使用者\“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 服務 (WinHTTP)