65.9K
CodeProject is changing. Read more.
Home

Asynchronous WinHTTP Library

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (5 votes)

Dec 11, 2009

CPOL
viewsIcon

53650

downloadIcon

3002

Tiny WinHTTP API wrapper library for asynchronous HTTP with callback handler

Introduction

The AsyncWinHttp is a simple wrapper of WinHTTP to achieve asynchronous HTTP. WinHtpp API is a replacement of WinINet API (see About WinHTTP for more information of why Microsoft recommends to use WinHttp API).

The library provides a very simple interface, the user can register a callback function when initializing the class. And the callback will be invoked when HTTP finished. The interface is shown as:

Background

This code is based on the sample of WinHTTP from MSDN, with a wrapper for simple use. 

Using the Code

To use the library is very simple, all you need is the two files:

  • AsyncWinHttp.h
  • AsyncWinHttp.cpp

First, you need to define your callback functions. These functions will be invoked when HTTP finished (whether succeeded or failed):

void WinHttp_CallBack(AsyncWinHttp* asyncWinHttp)
{
  // check if success or failed
  if (asyncWinHttp->status.Status() == ASYNC_WINHTTP_ERROR)
  {
    // print error message
    printf("%S", asyncWinHttp->status.Desc().c_str());
  }
  else // success
  {
    // print response, do your handling here ...
    std::string response;
    asyncWinHttp->GetResponseRaw(response);
    printf("%s", response.c_str());
  }
}

Now you can invoke the request to HTTP resources:

{
  AsyncWinHttp http;
  http.Initialize(WinHttp_CallBack);
  http.SetTimeout(3 * 60 * 1000);  // time out is 3 minutes
  http.SendRequest(L"http://www.google.cn");
}

Of course, you can use a Windows event to wait for the asynchronous HTTP call to finish, as shown in the demo, but I think most of you will not do so, since we need a really asynchronous HTTP. ;)

History

  • 11th December, 2009: Initial post