How to Download a File on WinInet.DLL


1. Create a new function that takes the URL as its single parameter, using this code:std::string GetUrl(const char *URL)
{
2. Insert this code to create a new constant buffer to store the size of the parts that make up your file:const int DownloadBufferSize = 1024;
3. Add this code to create a constant that stores errors, in case your program throws one:const std::string errorString = "ERROR";
4. Use the HINTERNET function of WinInet to open an Internet connection, before you attempt to download the file, by inserting this code:HINTERNET hInternet = InternetOpen("GINA: Version 0.1", INTERNET_OPEN_TYPE_DIRECT, NULL, 0,0);
if(hInternet == NULL){
return errorString;
}
5. Open the URL by using this code:HINTERNET hFile = InternetOpenUrl(hInternet, URL, NULL, 0, 0, 0);
if(hFile == NULL){
return errorString;
}
6. Create a buffer that holds file size by inserting this code:DWORD sizeBuffer;
DWORD length = sizeof(sizeBuffer);
7. Get the file size by using this code:bool succeeds = HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &sizeBuffer, &length, NULL) == TRUE;
8. Create a new string to store the file by inserting this code:std::string downloadedContents = "";
9. Insert this code to set the download buffer and count the number of bytes your program downloads:char *downloadBuffer = new char[DownloadBufferSize];
DWORD bytesRead = 0;
do{
InternetReadFile(hFile, downloadBuffer, DownloadBufferSize, &bytesRead);
10. Append the contents of the download buffer to the file until the file is complete by using this code:downloadedContents.append(downloadBuffer, DownloadBufferSize);
}while(bytesRead != 0);
11. Close the WinInet handles and the program by using this code:InternetCloseHandle(hFile);
InternetCloseHandle(hInternet);
return downloadedContents;
}

0 comments:

Post a Comment