2015-12-16 45 views
1

我在本地使用WinInet時遇到問題。我有一個運行良好的本地Apache網絡服務器(xampp),問題是當我嘗試向PHP腳本發出GET請求時,它似乎只做了一次。 PHP腳本只是輸出一個隨機數,我看到相同的數字3次(腳本沒有錯)。我也檢查了Apache訪問日誌,它只顯示一次。奇怪的是,當不在本地使用它時,循環完美地工作,它發出多個請求(Wireshark也顯示了這一點)。C++ WinInet只發出1個請求

下面是代碼,簡化,仍然給問題:

#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"); 
} 

我似乎無法想出解決辦法...

回答

1

我無法重現你的觀察,如果我查詢了示例www.google.com

我認爲你的程序只是用InternetReadFile繼續讀取響應,但你的機器上的其他進程還沒有完成請求。我建議在閱讀響應內容之前等待使用WinHttpReceiveResponse完成請求。

關於您的實現做更多的事情:

  • 你並不需要調用InternetOpen(..)爲每個新的要求。只需執行一次操作即可存儲返回的句柄,直到應用程序終止。

  • 檢查錯誤非常重要!你的功能只是依靠所有的電話成功,這顯然不是由於你的問題的情況下...