Click here to Skip to main content
15,120,268 members
Articles / Desktop Programming / Win32
Tip/Trick
Posted 12 Jan 2012

Stats

36K views
17 bookmarked

Alternative to URLDownloadToFile function

Rate me:
Please Sign up or sign in to vote.
3.38/5 (4 votes)
5 Oct 2021CPOL
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)

Share

About the Author

Ștefan-Mihai MOGA
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

 
GeneralPlease Can you tell me how to show Upload and Download in gr... Pin
Member 856969016-Jan-12 20:13
MemberMember 856969016-Jan-12 20:13 
Please Can you tell me how to show Upload and Download in graph form and log to file...
and Also show total upload/download over periods and total across application Session.

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.