Click here to Skip to main content
15,499,289 members
Articles / Desktop Programming / ATL
Posted 19 Mar 2010

Tagged as


312 bookmarked

A Fully Featured Windows HTTP Wrapper in C++

Rate me:
Please Sign up or sign in to vote.
4.92/5 (102 votes)
22 Sep 2010CPOL3 min read
A fully featured and easy-to-use Windows HTTP wrapper in C++


This is a fully featured Windows HTTP Wrapper in C++. It is a wrapper in the C++ class. It is fully featured and easy to use. You only need to include one single header file to use the wrapper.


Several months ago, I posted my first article A Simple Windows HTTP Wrapper Using C++ on CodeProject. I continued to update it in the last several months and finally got the fully featured Windows HTTP Wrapper based on WinHTTP APIs in C++.


  • Cookies supported
  • Proxy supported
  • GET, POST methods supported
  • Request headers customization supported
  • Disable automatic redirection supported
  • HTTPS supported
  • Receive progress supported
  • Some other features

Using the Code

The class diagram is as follows:


You can understand most of the functions from their names. Please refer to the examples section for some typical examples.


Simple Get Request

Get request is the most common request. Browsing a web page causes one or several Get requests.

// Set URL.
WinHttpClient client(L"");
// Send HTTP request, a GET request by default.
// The response header.
wstring httpResponseHeader = client.GetResponseHeader();
// The response content.
wstring httpResponseContent = client.GetResponseContent();

Simple Post Request

Post request usually occurs while logging in or posting a thread.

WinHttpClient client(L"");
// Set post data.
string data = "title=A_NEW_THREAD&content=This_is_a_new_thread.";
client.SetAdditionalDataToSend((BYTE *)data.c_str(), data.size());
// Set request headers.
wchar_t szSize[50] = L"";
swprintf_s(szSize, L"%d", data.size());
wstring headers = L"Content-Length: ";
headers += szSize;
headers += L"\r\nContent-Type: application/x-www-form-urlencoded\r\n";
// Send HTTP post request.
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Getting Request's Progress

You can specify a callback function to get the request's progress.

// Progress - finished percentage.
bool ProgressProc(double progress)
    wprintf(L"Current progress: %-.1f%%\r\n", progress);
    return true;
void ProgressTest(void)
    // Set URL and call back function.
    WinHttpClient client(L"", ProgressProc);
    wstring httpResponseHeader = client.GetResponseHeader();
    wstring httpResponseContent = client.GetResponseContent();

Specifying the User Agent

User agent is a string used by the clients to identify themselves to the web server so that the server can tell which client software you use, Internet Explorer 8, Chrome or FireFox. You can specify the user agent to pretend to be Internet Explorer 8 to fool the web server because sometimes the server only supports Internet Explorer 8.

WinHttpClient client(L"");
// Set the user agent to the same as Internet Explorer 8.
client.SetUserAgent(L"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;...)");
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Specifying the Proxy

Sometimes, we have to connect to the web through proxies. WinHttpClient connects to the web server directly and then uses the Internet Explorer setting to connect if it fails by default. You can also specify the proxy by calling function SetProxy.

WinHttpClient client(L"");
// Set the proxy to with port 8080.
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Handling Cookies

A cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small piece of text stored on a user's computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information.

The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server. A cookie can be used for authentication, session tracking (state maintenance), storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing textual data (

You can specify cookies to send by calling SetAdditionalRequestCookies and get the response cookies by calling GetResponseCookies.

WinHttpClient client(L"");
// Set the cookies to send.
// Get the response cookies.
wstring httpResponseCookies = client.GetResponseCookies();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();


WinHttpClient client(L"");

// Accept any certificate while performing HTTPS request.

wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Multiple Requests

WinHttpClient client(L"");
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

// Update the URL.
httpResponseHeader = client.GetResponseHeader();
httpResponseContent = client.GetResponseContent();

A Complete Example needs logging in to download the files. This example logs in, gets the cookies, requests the source code (win_HTTP_wrapper/ of my first CodeProject article, A Simple Windows HTTP Wrapper Using C++, and then saves the file to hard disk. This example includes cookies handling, post requests, request headers customization, etc.

// 1. Get the initial cookie.
WinHttpClient getClient
	(L"Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, ...");
if (!getClient.SendHttpRequest())
// 2. Post data to get the authentication cookie.
WinHttpClient postClient
// Post data.
wstring username = L"YourCodeProjectUsername";
wstring password = L"YourPassword";
string data = "FormName=MenuBarForm&Email=";
data += (char *)_bstr_t(username.c_str());
data += "&Password=";
data += (char *)_bstr_t(password.c_str());
data += "&RememberMeCheck=1";
postClient.SetAdditionalDataToSend((BYTE *)data.c_str(), data.size());
// Post headers.
wstring headers = L"...Content-Length: %d\r\nProxy-Connection: 
		Keep-Alive\r\nPragma: no-cache\r\n";
wchar_t szHeaders[MAX_PATH * 10] = L"";
swprintf_s(szHeaders, MAX_PATH * 10, headers.c_str(), data.size());
if (!postClient.SendHttpRequest(L"POST", true))
// 3. Finally get the zip file.    
WinHttpClient downloadClient(L"win_HTTP_wrapper/");
		(compatible; MSIE 8.0; Windows NT 5.1; ...)");
// Sending this cookie makes the server believe you have already logged in.
if (!downloadClient.SendHttpRequest())

Points of Interest

  • Sometimes, it is a good idea to get a piece of new code working first and improve it later.
  • Reading the Hypertext Transfer Protocol (RFC 2616) will help a lot.
  • Use HTTP monitoring tools to help the development, such as HTTPAnalyzer or HTTPWatch.
  • It is fast and easy to use class _bstr_t to convert between wchar_t* and char*.


  • 2010-9-21 2 enhancements, thanks Scott Leckie
  • 2010-4-29 2 Bugs fixed, thanks Wong Shao Voon
  • 2009-9 Fully featured version
  • 2008-7 Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer Philips
China China
Cheng Shi is a software developer in China. He is interested in COM, ATL, Direct3D, etc. He is now working for Philips.

Cheng Shi loves Formula1 and watchs every Grand Prix. He is dreaming to be a racing car driver. Hope his dream can come true.

Comments and Discussions

Bugnon ANSI characters Pin
Member 1500394417-Aug-21 9:15
MemberMember 1500394417-Aug-21 9:15 
QuestionHow to fix "no such name or directory" error Pin
T1xT18-Jun-21 23:45
MemberT1xT18-Jun-21 23:45 
BugYou have a bug in WinHttpClient.h Pin
Member 147863499-Feb-21 11:04
MemberMember 147863499-Feb-21 11:04 
QuestionCompile error in WinHttpClient.h on first example - found fix Pin
JackSimmons8-Sep-20 10:52
MemberJackSimmons8-Sep-20 10:52 
Questionsend file Pin
mattmail110-Aug-19 20:54
Membermattmail110-Aug-19 20:54 
BugI found a small bug Pin
Per Nilsson27-Dec-18 0:08
MemberPer Nilsson27-Dec-18 0:08 
I've found a small bug in the otherwise very nice software. The bug is located in the SendHttpRequest method.

The bug is in the part that reads the response content of the request.
There is a buffer that holds all received characters that are red from the socket. This buffer shall contain a null termination character after last received character. The buffer is filled with zeroes when allocated and when buffer is filled this will ensure that the character right after the last character in the buffer is 0. BUT, if we from WinHttpReadData read exactly the same number of characters that is available in the buffer, we will fill the buffer and we don't have room for a null termination character.

One solution is to add + 1 to the if statement that makes the decision to increase the buffer size.
if (dwRead + iCurrentBufferSize + 1 > iMaxBufferSize)

    dwSize = 0;
    if (::WinHttpQueryDataAvailable(hRequest, &dwSize))
        BYTE *pResponse = new BYTE[dwSize + 1];
        if (pResponse != NULL)
            memset(pResponse, 0, (dwSize + 1)*sizeof(BYTE));
            DWORD dwRead = 0;
            if (::WinHttpReadData(hRequest,
                if (dwRead + iCurrentBufferSize + 1 > iMaxBufferSize)
                    BYTE *pOldBuffer = m_pResponse;
                    m_pResponse = new BYTE[iMaxBufferSize * 2];
                    if (m_pResponse == NULL)
                        m_pResponse = pOldBuffer;
                        bRetVal = false;
                    iMaxBufferSize *= 2;
                    memset(m_pResponse, 0, iMaxBufferSize);
                    memcpy(m_pResponse, pOldBuffer, iCurrentBufferSize);
                    delete[] pOldBuffer;
                memcpy(m_pResponse + iCurrentBufferSize, pResponse, dwRead);
                iCurrentBufferSize += dwRead;
            delete[] pResponse;
        m_dwLastError = ::GetLastError();
while (dwSize > 0);

QuestionSend PUT request Pin
Member 139410648-Aug-18 9:07
MemberMember 139410648-Aug-18 9:07 
QuestionHttp DELETE Pin
Member 1285026314-Jun-18 9:53
MemberMember 1285026314-Jun-18 9:53 
QuestionDoes not work with MinGW, also, should switch to using std::Regex Pin
robstoddard9-Apr-18 7:01
Memberrobstoddard9-Apr-18 7:01 
Questionit doesn't works with windows xp somehow Pin
sandeepcyber28-Oct-17 2:13
Membersandeepcyber28-Oct-17 2:13 
QuestionSend data in POST body Pin
Member 1337088819-Oct-17 10:45
MemberMember 1337088819-Oct-17 10:45 
GeneralThis is not multi-platform Pin
Jaime Stuardo - Chile12-Apr-17 8:27
MemberJaime Stuardo - Chile12-Apr-17 8:27 
GeneralTLS 1.2 Support Pin
Member 946680624-Mar-17 6:43
MemberMember 946680624-Mar-17 6:43 
GeneralRe: TLS 1.2 Support Pin
cdichter9-Nov-17 10:49
Membercdichter9-Nov-17 10:49 
QuestionIs there any way to call "PUT" webservice with this code? Pin
nallana vijayakumar17-Nov-16 20:18
Membernallana vijayakumar17-Nov-16 20:18 
AnswerRe: Is there any way to call "PUT" webservice with this code? Pin
lmarcos_Etra9-Feb-17 2:20
Memberlmarcos_Etra9-Feb-17 2:20 
AnswerRe: Is there any way to call "PUT" webservice with this code? Pin
Member 1398642516-Sep-18 10:49
MemberMember 1398642516-Sep-18 10:49 
Questionredirect header Pin
Chandrak Baxi25-Dec-15 22:27
MemberChandrak Baxi25-Dec-15 22:27 
SuggestionStudents will not make it Pin
Member 84741974-Apr-15 15:47
MemberMember 84741974-Apr-15 15:47 
GeneralRe: Students will not make it Pin
Genkobar16-Jun-15 17:33
MemberGenkobar16-Jun-15 17:33 
SuggestionHttps example Pin
Member 1067569217-Mar-14 0:06
MemberMember 1067569217-Mar-14 0:06 
QuestionFew include files missing Pin
Pandian Raju17-Feb-14 10:28
MemberPandian Raju17-Feb-14 10:28 
QuestionUser and password Authentication Pin
reivaj117 19-Dec-13 2:57
Memberreivaj117 19-Dec-13 2:57 
AnswerRe: User and password Authentication Pin
shicheng22-Dec-13 1:34
Membershicheng22-Dec-13 1:34 
Questionwchar_t compile errors in RegExp.h Pin
Vern Jensen12-Dec-13 17:47
MemberVern Jensen12-Dec-13 17:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.