int CUpdate::Download(const char* src, const char* des)
{
HINTERNET internet = InternetOpen("HTTP Downloader", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL) ;
if (internet == INVALID_HANDLE_VALUE || NULL == internet)
{
return -1;
}
HINTERNET file_handle = InternetOpenUrl(internet, src, NULL, 0, INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE/*INTERNET_FLAG_DONT_CACHE*/, 0) ;
if (NULL == file_handle || INVALID_HANDLE_VALUE == file_handle)
{
InternetCloseHandle(internet) ;
return -2;
}
ULONG uk = 0;
DWORD dwStatusCode = 0;
DWORD dwStatusSize = sizeof(dwStatusCode);
if (FALSE == ::HttpQueryInfo(file_handle,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
&dwStatusCode,
&dwStatusSize,
&uk)) //获取返回状态码
{
InternetCloseHandle(internet) ;
InternetCloseHandle(file_handle);
return -3;
}
//判断状态码是不是 200
if (HTTP_STATUS_OK != dwStatusCode)
{
InternetCloseHandle(internet) ;
InternetCloseHandle(file_handle);
return -4;
}
HANDLE hFile = CreateFile(des, GENERIC_ALL, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
InternetCloseHandle(internet) ;
InternetCloseHandle(file_handle);
return -5;
}
DWORD dwReadDataLength = NULL;
BOOL bRet = TRUE;
// 下面将读取的内容写入本地文件中
//std::string::size_type nPos = strTmpPath.rfind("\\") ;
//std::string strFileName = strTmpPath.substr(nPos + 1)
DWORD dwMaxDataLength = 1024;
char* pBuffer = new char[dwMaxDataLength + 1];
do
{
DWORD dwWritenSize = 0;
ZeroMemory(pBuffer,dwMaxDataLength);
bRet = InternetReadFile(file_handle,pBuffer,dwMaxDataLength,&dwReadDataLength);
if(bRet == TRUE)
{
pBuffer[dwReadDataLength] = 0 ;
WriteFile(hFile, pBuffer, dwReadDataLength, &dwWritenSize, NULL);
}
} while (NULL != dwReadDataLength);
if(pBuffer)
delete[] pBuffer;
InternetCloseHandle(internet) ;
InternetCloseHandle(file_handle);
CloseHandle(hFile);
return 0;
}
DWORD CUpdate::GetFileSize(const char* file)
{
DWORD dwLen = 0;
HANDLE hFile = CreateFile(file, GENERIC_ALL, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile != INVALID_HANDLE_VALUE)
{
dwLen = ::GetFileSize(hFile, NULL);
CloseHandle(hFile);
}
return dwLen;
}