剛學C++,想用winhttp做一些測驗
void QtGuiApplication::getBtnClick() {
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
// www.microsoft.com
hConnect = WinHttpConnect(hSession, L"127.0.0.1",
INTERNET_DEFAULT_HTTPS_PORT, 0);
// Create an HTTP request handle.
if (hConnect) {
hRequest = WinHttpOpenRequest(hConnect, L"GET", NULL,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE);
}
// Send a request.
if (hRequest)
bResults = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
// End the request.
if (bResults) {
bResults = WinHttpReceiveResponse(hRequest, NULL);
}
else {
qDebug("Error has WinHttpSendRequest");
QString errorStr = QString::number(GetLastError());
qDebug(qPrintable(errorStr));
}
// Keep checking for data until there is nothing left.
if (bResults)
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
dwSize = 0;
}
else
{
// Read the Data.
ZeroMemory(pszOutBuffer, dwSize + 1);
if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
printf("Error %u in WinHttpReadData.\n", GetLastError());
else
qDebug(pszOutBuffer);
// Free the memory allocated to the buffer.
delete[] pszOutBuffer;
}
} while (dwSize > 0);
// Report any errors.
if (!bResults) {
qDebug("Error has occurred");
QString str = QString::number(GetLastError());
qDebug(qPrintable(str));
}
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
}

這里我是隨便用 springboot 起了個服務器, 127.0.0.1 埠 80, 直接瀏覽時是可以訪問的。用winhttp的api,到WinHttpSendRequest 這一步就不是有效句柄了,之前的都是有效句柄。 有沒有大佬遇到這樣的問題。qaq
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/61229.html
標籤:Windows客戶端開發
上一篇:Android stusio 修改代碼后模擬器無改變
下一篇:GUI中自定義事件的觸發
