使用 WinHttp 实现文件下载

时间:2022-07-06 21:57:07
 #include <Windows.h>
#include <Winhttp.h>
#pragma comment(lib,"Winhttp.lib") typedef struct _URL_INFO
{
WCHAR szScheme[];
WCHAR szHostName[];
WCHAR szUserName[];
WCHAR szPassword[];
WCHAR szUrlPath[];
WCHAR szExtraInfo[];
}URL_INFO, *PURL_INFO; int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd )
{
URL_INFO url_info = {};
URL_COMPONENTSW url = {};
url.dwStructSize = sizeof(url);
url.lpszExtraInfo = url_info.szExtraInfo;
url.lpszHostName = url_info.szHostName;
url.lpszPassword = url_info.szPassword;
url.lpszScheme = url_info.szScheme;
url.lpszUrlPath = url_info.szUrlPath;
url.lpszUserName = url_info.szUserName; url.dwExtraInfoLength =
url.dwHostNameLength =
url.dwPasswordLength =
url.dwSchemeLength =
url.dwUrlPathLength =
url.dwUserNameLength = ; WinHttpCrackUrl(L"http://www.pediy.com/tools/Debuggers/ollydbg/OllyICE.rar", , ICU_ESCAPE, &url); // 创建一个会话
HINTERNET hSession = WinHttpOpen(NULL, WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, );
BYTE *pBuffer = NULL;
DWORD dwReadBytes, dwSizeDW = sizeof(dwSizeDW), dwContentSize, dwIndex = ;
// 创建一个连接
HINTERNET hConnect = WinHttpConnect(hSession, url.lpszHostName, url.nPort, );
// 创建一个请求,先查询内容的大小
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"HEAD", url.lpszUrlPath, L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, , WINHTTP_NO_REQUEST_DATA, , , );
WinHttpReceiveResponse(hRequest, );
WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwContentSize, &dwSizeDW, &dwIndex);
WinHttpCloseHandle(hRequest); // 创建一个请求,获取数据
hRequest = WinHttpOpenRequest(hConnect, L"GET", url.lpszUrlPath, L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, , WINHTTP_NO_REQUEST_DATA, , , );
WinHttpReceiveResponse(hRequest, );
pBuffer = new BYTE[dwContentSize];
ZeroMemory(pBuffer, dwContentSize);
WinHttpReadData(hRequest, pBuffer, dwContentSize, &dwReadBytes); HANDLE hFile = CreateFileW(L"c:\\ollydbg.rar", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile, pBuffer, dwContentSize, &dwReadBytes, NULL);
CloseHandle(hFile); delete pBuffer; WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession); return ;
}