Search code examples
c++webhttpsputwinhttp

How to reuse the same HTTPS connection for many put requests within a session?


To send files to server, I do a HTTPS put request in Windows, which looks like this:

hSession = WinHttpOpen(  L"Agent/1.0",..
hConnect = WinHttpConnect(hSession,..
hRequest = WinHttpOpenRequest( hConnect, L"PUT",..
WinHttpSetCredentials(hRequest,..
WinHttpAddRequestHeaders( hRequest,..
WinHttpSendRequest( hRequest,..
WinHttpWriteData(hRequest,..
WinHttpReceiveResponse(hRequest,..
WinHttpQueryHeaders(hRequest,..
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);

This pack of command is run for every file, which should be sent to server. Establishing the connection from scratch for every file to be sent creates additional overhead. Now I'm looking for a way to reduce this overhead.

So I have two questions:

  • Is it necessary to open and close a new HTTPS connection for each put request?
  • Is there a way to establish a session and reuse the same HTTPS connection for many put requests within this session?

Solution

  • The answers are the following:

    1. No. One connection may perform a bunch of requests.
    2. This is the draft of the code:

      hSession = WinHttpOpen( L"Agent/1.0",..
      hConnect = WinHttpConnect(hSession,.. 
      for (all_files_to_upload) { 
          hRequest = WinHttpOpenRequest( hConnect, L"PUT",..
          WinHttpSetCredentials(hRequest,.. 
          WinHttpAddRequestHeaders( hRequest,.. 
          WinHttpSendRequest( hRequest,.. 
          WinHttpWriteData(hRequest,.. 
          WinHttpReceiveResponse(hRequest,.. 
          WinHttpQueryHeaders(hRequest,.. 
          WinHttpCloseHandle(hRequest);
      } 
      
      if (hConnect) WinHttpCloseHandle(hConnect);
      if (hSession) WinHttpCloseHandle(hSession);