【发布时间】:2015-12-16 20:37:41
【问题描述】:
我在本地使用 WinInet 时遇到问题。我有一个运行良好的本地 Apache 网络服务器 (xampp),问题是当我尝试向 PHP 脚本发出 GET 请求时,它似乎只执行一次。 PHP 脚本只是输出一个随机数,我看到相同的数字 3 次(脚本没有错误)。我还检查了 Apache 访问日志,它只显示一次。奇怪的是,当不在本地使用它时,循环完美地工作并且它确实发送了多个请求(Wireshark 也显示了这一点)。
这里是代码,简化但仍然存在问题:
#include <Windows.h>
#include <WinInet.h>
#include <iostream>
#include <string>
#pragma comment(lib, "wininet.lib")
void req()
{
HINTERNET hInternet = InternetOpenW(L"useragent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET hConnect = InternetConnectW(hInternet, L"127.0.0.1", 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
HINTERNET hRequest = HttpOpenRequestW(hConnect, L"GET", L"test/test.php", NULL, NULL, NULL, 0, 0);
BOOL bRequestSent = HttpSendRequestW(hRequest, NULL, 0, NULL, 0);
std::string strResponse;
const int nBuffSize = 1024;
char buff[nBuffSize];
BOOL bKeepReading = true;
DWORD dwBytesRead = -1;
while (bKeepReading && dwBytesRead != 0)
{
bKeepReading = InternetReadFile(hRequest, buff, nBuffSize, &dwBytesRead);
strResponse.append(buff, dwBytesRead);
}
std::cout << strResponse << std::endl;
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
}
int main()
{
for (int x = 0;x < 3; x++) // 3 times
{
req();
Sleep(2000);
}
system("PAUSE");
}
我似乎无法弄清楚...
【问题讨论】: