bool DownLoad(LPCWSTR _url, QString strfile)
{
QByteArray arr = strfile.toLocal8Bit();
const char* _file_name = arr.data();
FILE* fp_download = fopen(_file_name, "wb");
if (fp_download == NULL)
{
return false;
}
HINTERNET innet_open = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (innet_open == NULL)
{
fclose(fp_download);
return false;
}
HINTERNET innet_url = InternetOpenUrl(innet_open, _url, NULL, 0, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_PRAGMA_NOCACHE, 0);
if (innet_url == NULL)
{
InternetCloseHandle(innet_url);
return false;
}
//检查状态码
DWORD http_status;
DWORD http_status_size = sizeof(http_status);
HttpQueryInfo(innet_url, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &http_status, &http_status_size, NULL);
if (http_status != 200)
{
InternetCloseHandle(innet_url);
InternetCloseHandle(innet_open);
return false;
}
//获取接收数据大小
DWORD file_length = 0;
DWORD file_length_size = sizeof(file_length);
HttpQueryInfo(innet_url, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &file_length, &file_length_size, NULL);
if (file_length < 0)
{
InternetCloseHandle(innet_url);
InternetCloseHandle(innet_open);
return FALSE;
}
DWORD res_len = 1;
DWORD read_len = 0;
uint8_t temp_buf[DOWNLOAD_BUFFER_SIZE] = { 0 };
while (true)
{
memset(temp_buf, 0, sizeof(uint8_t) * res_len);
InternetReadFile(innet_url, temp_buf, DOWNLOAD_BUFFER_SIZE, &res_len);
if (res_len <= 0)
break;
if (res_len == fwrite(temp_buf, sizeof(uint8_t), res_len, fp_download))
{
read_len += res_len;
}
}
InternetCloseHandle(innet_url);
InternetCloseHandle(innet_open);
fclose(fp_download);
return true;
}
void main()
{
if(true == DownLoad(L"https://eval.zhihuiyunji.com/riskclient_update/", fileName)
{
//下载成功就解析文件,读取内容
}
}
C++实现文件下载功能
最新推荐文章于 2024-05-30 23:53:18 发布