C++爬虫模板3.1(winhttp)
由于原始代码已经是一个很好的示例,下面提供的代码是一个简化版本,去除了原始代码中的一些复杂性,并添加了必要的注释。
#include <iostream>
#include <string>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
bool GetHttpFile(const std::wstring& url, const std::wstring& filename) {
HINTERNET hSession = ::WinHttpOpen(L"Crawler/3.1", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) {
std::cerr << "WinHttpOpen failed: " << GetLastError() << std::endl;
return false;
}
HINTERNET hConnect = ::WinHttpConnect(hSession, L"www.example.com", INTERNET_DEFAULT_HTTP_PORT, 0);
if (!hConnect) {
std::cerr << "WinHttpConnect failed: " << GetLastError() << std::endl;
::WinHttpCloseHandle(hSession);
return false;
}
HINTERNET hRequest = ::WinHttpOpenRequest(hConnect, L"GET", url.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hRequest) {
std::cerr << "WinHttpOpenRequest failed: " << GetLastError() << std::endl;
::WinHttpCloseHandle(hConnect);
::WinHttpCloseHandle(hSession);
return false;
}
if (!::WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
std::cerr << "WinHttpSendRequest failed: " << GetLastError() << std::endl;
::WinHttpCloseHandle(hRequest);
::WinHttpCloseHandle(hConnect);
::WinHttpCloseHandle(hSession);
return false;
}
if (!::WinHttpReceiveResponse(hRequest, NULL)) {
std::cerr << "WinHttpReceiveResponse failed: " << GetLastError() << std::endl;
::WinHttpCloseHandle(hRequest);
::WinHttpCloseHandle(hConnect);
::WinHttpCloseHandle(hSession);
return false;
}
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
std::ofstream outfile(filename, std::ios::out | std::ios::binary);
if (outfile) {
do {
char buffer[4096];
if (!::WinHttpQueryDataAvailable(hRequest, &dwSize)) {
std::cerr << "WinHttpQueryDataAvailable failed: " << GetLastError() << std::endl;
::WinHttpCloseHandle(hRequest);
::WinHttpCloseHandle(hConnect);
::WinHttpCloseHandle(hSession);
return false;
}
if (!dwSize) {
break;
}
if (!::WinHttpReadDa
评论已关闭