Click here to Skip to main content
15,868,158 members
Articles / Desktop Programming / Win32
Tip/Trick

Alternative to URLDownloadToFile function

Rate me:
Please Sign up or sign in to vote.
3.74/5 (10 votes)
20 Aug 2023CPOL 41.3K   18   1
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)


Written By
Software Developer NXP Semiconductors
Romania Romania
My professional background includes knowledge of analyst programmer for Microsoft Visual C++, Microsoft Visual C#, Microsoft Visual Basic, Sun Java, assembly for Intel 80x86 microprocessors, assembly for PIC microcontrollers (produced by Microchip Inc.), relational databases (MySQL, Oracle, SQL Server), concurrent version systems, bug tracking systems, web design (HTML5, CSS3, XML, PHP/MySQL, JavaScript).

Comments and Discussions

 
SuggestionMissing functionality Pin
Sergey Alexandrovich Kryukov20-Aug-23 18:21
mvaSergey Alexandrovich Kryukov20-Aug-23 18:21 

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.