Code:
bool X3DNet_DownloadFile(const char *url, const char *filename,
bool binary, const char *username,
const char *password)
{
HINTERNET hOpenHandle, hResourceHandle, hConnectHandle;
DWORD dwError, dwStatus;
DWORD dwStatusSize = sizeof(dwStatus);
DWORD dwUserNameLength = strlen(username);
DWORD dwPasswordLength = strlen(password);
char buffer[1024];
char sUserName[80];
char sPassword[80];
FILE *fout = NULL;
DWORD dwRead;
strcpy(sUserName, username);
strcpy(sPassword, password);
// Start the internet session
hOpenHandle = InternetOpen("auth",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hOpenHandle == NULL) {
X3DUtil_Log("Starting the internet session failed.");
return false;
}
// Connect to url.
hConnectHandle = InternetConnect(hOpenHandle, url,
INTERNET_INVALID_PORT_NUMBER, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (hConnectHandle == NULL) {
X3DNet_CloseHandle(hOpenHandle);
return false;
}
// Open the Request
hResourceHandle = HttpOpenRequest(hConnectHandle, "GET",
url, NULL,
NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0);
if (hResourceHandle == NULL)
{
X3DNet_CloseHandle(hOpenHandle);
return false;
}
// Send Request
if (!HttpSendRequest(hResourceHandle, NULL, 0, NULL, 0))
{
if (GetLastError() == 12005)
{
X3DNet_CloseHandle(hOpenHandle);
X3DNet_CloseHandle(hResourceHandle);
X3DUtil_Log("URL is invalid.");
return false;
}
}
// Retreive State
if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER |
HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL))
{
X3DNet_CloseHandle(hOpenHandle);
X3DNet_CloseHandle(hResourceHandle);
X3DNet_CloseHandle(hConnectHandle);
return false;
}
// Proxy Authentication Required
if ((dwStatus == HTTP_STATUS_PROXY_AUTH_REQ) || (dwStatus == HTTP_STATUS_DENIED))
{
if (!InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_USERNAME,
sUserName, dwUserNameLength + 1))
return false;
if (!InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_PASSWORD,
sPassword, dwPasswordLength + 1))
return false;
}
// Open local file in binary or character.
fout = fopen(filename, ((binary) ? "wb" : "w"));
if (fout == NULL)
return false;
// Read in the file.
while (InternetReadFile(hResourceHandle, buffer, 1023, &dwRead))
{
if (dwRead == 0)
break;
buffer[dwRead] = 0;
fwrite(buffer, dwRead, 1, fout);
}
// Close resources.
X3DNet_CloseHandle(hOpenHandle);
X3DNet_CloseHandle(hResourceHandle);
X3DNet_CloseHandle(hConnectHandle);
fclose(fout);
return true;
}