Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Alternative to URLDownloadToFile function

3.74/5 (10 votes)
20 Aug 2023CPOL 42.4K  
How to download files from an HTTP server.
I have updated HTTP client

In response to a StackOverflow question[^], I developed an alternative for URLDownloadToFile function; it is based on a generic HTTP client[^] written in C++.

C++
CString FormatErrorMessage(DWORD dwLastError)
{
     const int nLength = 0x1000;
     TCHAR lpszBuffer[nLength] = { 0 };
 
     if (::FormatMessage(
         // FORMAT_MESSAGE_ALLOCATE_BUFFER |
         FORMAT_MESSAGE_FROM_SYSTEM,
         NULL,
         dwLastError,
         0,
         (LPTSTR) &lpszBuffer,
         nLength, NULL) == 0)
     {
         _stprintf_s(lpszBuffer, nLength, _T("Unknown INET error 0x%.4X\n"), dwLastError);
     }
     return lpszBuffer;
}
 
HRESULT DownloadURLToFile(CString strURLDownload, CString strFilePath)
{
     CHTTPClient httpClient;
     httpClient.EnableStatusCallback(TRUE);
     httpClient.InitilizePostArguments();
     httpClient.SetDownloadFile(strFilePath);
 
     BOOL bResult = httpClient.Request(
         strURLDownload,
         CHTTPClient::RequestGetMethod,
         __DEFAULT_AGENT_NAME);
     DWORD dwLastError = httpClient.GetLastError();
     OutputDebugString(_T("DownloadURLToFile: ") + FormatErrorMessage(dwLastError));
 
     LPBYTE lpszHttpResponse = httpClient.QueryHTTPResponse();
     return (bResult ? S_OK : E_FAIL);
}

License

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