我需要从大约6000页的网站中提取数据。经过一番研究,我决定给WinHTTP一个机会。我能够让这个工作,但我同步做事,所以需要一段时间才能完成。我现在正试图异步使用WinHTTP,但我遇到了障碍。我四处搜索了一些教程和示例,但我只能找到MSDN文档,这对我正在做的事情来说似乎过于复杂。如上所述,我找不到很多资源,所以我继续前进并试了一下:
std::string theSource = "";
char * httpBuffer;
DWORD dwSize = 1;
DWORD dwRecv = 1;
HINTERNET hOpen =
WinHttpOpen
(
L"Example Agent",
WINHTTP_ACCESS_TYPE_NO_PROXY,
NULL,
NULL,
WINHTTP_FLAG_ASYNC
);
WINHTTP_STATUS_CALLBACK theCallback =
WinHttpSetStatusCallback
(
hOpen,
(WINHTTP_STATUS_CALLBACK) HttpCallback,
WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
NULL
);
HINTERNET hConnect =
WinHttpConnect
(
hOpen,
L"example.org",
INTERNET_DEFAULT_HTTPS_PORT,
0
);
HINTERNET hRequest = NULL;
BOOL allComplete = false;
int theRequest = 1;
while (!allComplete)
{
if (theRequest == 1)
{
hRequest = WinHttpOpenRequest
(
hConnect,
L"GET",
L"example.html",
0,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE
);
WinHttpSendRequest
(
hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
WINHTTP_NO_REQUEST_DATA,
0,
0,
0
);
}
else if (theRequest == 2)
{
WinHttpReceiveResponse(hRequest, NULL);
}
else if (theRequest == 3)
{
WinHttpQueryHeaders
(
hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
NULL,
&dwSize,
WINHTTP_NO_HEADER_INDEX
);
WCHAR * headerBuffer = new WCHAR[dwSize/sizeof(WCHAR)];
WinHttpQueryHeaders
(
hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
headerBuffer,
&dwSize,
WINHTTP_NO_HEADER_INDEX
);
delete [] headerBuffer;
dwSize = 1;
while (dwSize > 0)
{
if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
{
break;
}
httpBuffer = new char[dwSize + 1];
ZeroMemory(httpBuffer, dwSize + 1);
if (!WinHttpReadData(hRequest, httpBuffer, dwSize, &dwRecv))
{
std::cout << "WinHttpReadData() - Error Code: " << GetLastError() << "\n";
}
else
{
theSource = theSource + httpBuffer;
}
delete [] httpBuffer;
// Parse the source for the data I'm looking for.
break;
}
}
以下是我的回调函数:
void CALLBACK HttpCallback(HINTERNET hInternet, DWORD * dwContext, DWORD dwInternetStatus, void * lpvStatusInfo, DWORD dwStatusInfoLength)
{
switch (dwInternetStatus)
{
default:
std::cout << dwInternetStatus << "\n";
break;
case WINHTTP_CALLBACK_STATUS_HANDLE_CREATED:
std::cout << "Handle created.\n";
theRequest = 1;
break;
case WINHTTP_CALLBACK_STATUS_REQUEST_SENT:
std::cout << "Request sent.\n";
theRequest = 2;
break;
case WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED:
std::cout << "Response received.\n";
theRequest = 3;
break;
}
}
注意:我只提供了我的代码的这一部分,因为它是与我的问题/问题相关的部分。如果缺少变量声明,我道歉。
上面的代码对我有用,并且确实可以获得我正在寻找的所需信息,但仅适用于单个页面。在达到这一点之后,我意识到在使用此方法发出多个请求时,我不知道该怎么做。同样,除了MSDN文章之外,搜索没有多少,据我所知,这些文章不是一次发出多个请求的例子。另外,我正在使用while循环打开/发送/等。基于theRequest值的请求似乎是一种可怕的方式。我也很感激任何其他建议来改进我的代码。
一般来说,这里是我的问题的摘要:我需要异步使用WinHTTP进行大约6000个GET请求。我不完全确定如何做到这一点因为我是WinHTTP的新手,所以我正在寻找最基本(或可能有效)的方式来处理多个异步请求。
答案 0 :(得分:2)
你要在while (!allComplete) { ... }
重复你正在做的事情并以这种方式发出更多请求。您可以重复使用hConnect
,但您需要为每个资源请求执行WinHttpOpenRequest
。