How to download a file from the internet
In order to be able to get the data for my little Q-Music versus Studio Brussel test, I needed a way to download the xml data from the aforementioned radio station's websites.
Downloading a small file in Delphi is relatively easy - in the following code snippet, I'll show you how this works.
First of all, here's the code: don't forget to include units SysUtils, Windows and WinInet in your program if you're going to use this snippet.
function GetFileFromURL(const location, filename : String) : boolean; const BUFFER_SIZE = 1024; var session : HInternet; url : HInternet; buffer : array[1..BUFFER_SIZE] of Byte; bufferLength : DWORD; f : File; begin session := InternetOpen('My application', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); try url := InternetOpenURL(session, PChar(location), nil, 0, INTERNET_FLAG_RELOAD, 0); try try AssignFile(f, filename); Rewrite(f); repeat InternetReadFile(url, @buffer, SizeOf(buffer), bufferLength); BlockWrite(f, buffer, bufferLength) until bufferLength = 0; finally CloseFile(f); end; result := True; finally InternetCloseHandle(url); end finally InternetCloseHandle(session); end end;
To download a file, call the function GetFileFromURL with the location (URL) of the file, and the name of the file where you want to store the downloaded content. That's it!
Although this code works as described above, there are some additional things worth mentioning:
- In InternetOpen you can specify the "agent" who performs the download. In this example, I used the hardcoded value of "My application", but you can of course change this to whatever string you want.
- The INTERNET_FLAG_RELOAD flag was VERY important to me: it makes sure the download is performed each time InternetOpenURL is called, in other words it ignores caching! If you don't care about real-time, up-to-date contents, you might want to specify the value 0 instead.
Have fun downloading!