2

What HTTP header exactly can be queried using WINHTTP_QUERY_URI flag with WinHttpQueryHeaders function? After reading its description I was under impression this flag was supposed to be used to get the URI of the request specified in WinHttpOpenRequest function. Yet the following program gives me an error code 12019 ERROR_INTERNET_INCORRECT_HANDLE_STATE (and 12150 ERROR_HTTP_HEADER_NOT_FOUND if I uncomment two commented lines).

#include <cstdio>
#include <windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
int main()
{
    HINTERNET hSession = WinHttpOpen(nullptr, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    HINTERNET hConnect = WinHttpConnect(hSession, L"www.ietf.org", INTERNET_DEFAULT_HTTP_PORT, 0);
    HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/rfc/rfc2616.txt", nullptr, WINHTTP_NO_REFERER, nullptr, 0);

    //WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
    //WinHttpReceiveResponse(hRequest, 0);

    wchar_t url[1024] = {};
    DWORD url_size = sizeof(url);
    auto success = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_URI, WINHTTP_HEADER_NAME_BY_INDEX, url, &url_size, WINHTTP_NO_HEADER_INDEX);
    auto error_code = GetLastError();
    wprintf(L"success=%d error_code=%u url=%s", success, error_code, url);

    WinHttpCloseHandle(hRequest);
    WinHttpCloseHandle(hConnect);
    WinHttpCloseHandle(hSession);
}

P.S. Yes, I know I can get request URI using WinHttpQueryOption and WINHTTP_OPTION_URL, no need to point that out.

EDIT. Adding WINHTTP_QUERY_FLAG_REQUEST_HEADERS flag as per Captain Obvlious answer below (which totally makes sense if WINHTTP_QUERY_URI was indeed supposed to return request URI) did not make much difference: now with or without WinHttpSendRequest and WinHttpReceiveResponse calls WinHttpQueryHeaders function produces error code 12150 ERROR_HTTP_HEADER_NOT_FOUND.

PowerGamer
  • 2,106
  • 2
  • 17
  • 33

1 Answers1

1

You are querying the response headers of the request which do not contain the URI. You need to include the WINHTTP_QUERY_FLAG_REQUEST_HEADERS modifier flag to retrieve from the request header.

WinHttpQueryHeaders(
    hRequest,
    WINHTTP_QUERY_URI | WINHTTP_QUERY_FLAG_REQUEST_HEADERS,
    WINHTTP_HEADER_NAME_BY_INDEX,
    url,
    &url_size,
    WINHTTP_NO_HEADER_INDEX);
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74