WinHTTP API Reference

WinHTTP – Windows HTTP Services

Introduction

The WinHTTP API provides developers with a set of functions for sending HTTP requests and receiving responses from a server. It is optimized for client-side applications and services that require high performance, secure communications, and fine‑grained control over HTTP behavior.

Initialization

To start using WinHTTP, open a session handle using WinHttpOpen. The session determines the user agent string and access type.

HINTERNET hSession = WinHttpOpen(
    L"MyApp/1.0",               // User-Agent
    WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
    WINHTTP_NO_PROXY_NAME,
    WINHTTP_NO_PROXY_BYPASS,
    0);
if (!hSession) {
    // Handle error
}

Sending Requests

After establishing a session, create a connection and request object.

HINTERNET hConnect = WinHttpConnect(hSession, L"api.example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
HINTERNET hRequest = WinHttpOpenRequest(
    hConnect,
    L"GET",
    L"/v1/resource",
    NULL,
    WINHTTP_NO_REFERER,
    WINHTTP_DEFAULT_ACCEPT_TYPES,
    WINHTTP_FLAG_SECURE);
WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0);

Receiving Responses

Read the status code and response data using WinHttpQueryHeaders and WinHttpReadData.

DWORD statusCode = 0;
DWORD size = sizeof(statusCode);
WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
    WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &size, WINHTTP_NO_HEADER_INDEX);

// Read body
DWORD dwSize = 0;
WinHttpQueryDataAvailable(hRequest, &dwSize);
if (dwSize > 0) {
    std::vector buffer(dwSize);
    DWORD dwRead = 0;
    WinHttpReadData(hRequest, buffer.data(), dwSize, &dwRead);
    // Process buffer
}

Error Handling

Inspect the return values of each WinHTTP function. Use GetLastError and the WinHTTP error codes (WINHTTP_ERROR_*) for troubleshooting.

if (!WinHttpSendRequest(...)) {
    DWORD err = GetLastError();
    // Map err to a friendly message
}