如何使用winhttp获取请求cookie?

时间:2015-08-01 08:16:34

标签: c++ winapi winhttp

响应cookie('Set-Cookie'响应头)获得了很好,但请求cookie('Cookie'请求头)我WinHttpQueryHeaders即使用WINHTTP_QUERY_FLAG_REQUEST_HEADERS也无法获取:

DWORD size = 0;
BOOL re = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_COOKIE /*| WINHTTP_QUERY_FLAG_REQUEST_HEADERS*/, nullptr, nullptr, &size, nullptr);
DWORD err = GetLastError(); // re = 0 && err == ERROR_WINHTTP_HEADER_NOT_FOUND

怎么了?

2 个答案:

答案 0 :(得分:0)

这应该有效:

DWORD lastError;
LPVOID lpBuffer;
DWORD dwSize = 0, dwIndex = 0;

// Call with zero size to get actual size
BOOL res = WinHttpQueryHeaders(hRequest,
        WINHTTP_QUERY_COOKIE,
        WINHTTP_HEADER_NAME_BY_INDEX,
        NULL,
        &dwSize,
        &dwIndex);
lastError = GetLastError();
if (lastError == ERROR_INSUFFICIENT_BUFFER)
{
    lpBuffer = new WCHAR[dwSize/sizeof(WCHAR)];
    WinHttpQueryHeaders(hRequest,
        WINHTTP_QUERY_COOKIE,
        WINHTTP_HEADER_NAME_BY_INDEX,
        lpBuffer,
        &dwSize,
        &dwIndex);

    // convert result to wstring
    std::wstring result(reinterpret_cast<wchar_t*>(lpBuffer),
        dwSize/sizeof(wchar_t));
    std::wcout << L"Result: " << result << endl;
    delete[] lpBuffer;
}

答案 1 :(得分:0)

我能够使用(WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_RAW_HEADERS_CRLF)组合检索请求标头(包括cookie),而不是仅使用WINHTTP_QUERY_RAW_HEADERS_CRLF作为响应标头。