QT5.6 下使用WinHTTP的GET 方法
时间: 2023-08-20 21:05:12 浏览: 86
在QT5.6下使用WinHTTP的GET方法,可以参考以下代码实现:
```cpp
#include <windows.h>
#include <winhttp.h>
QByteArray httpGet(QString url)
{
QByteArray result;
HINTERNET hSession = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
// Open session
hSession = WinHttpOpen(L"QT5.6 WinHTTP GET", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession)
return result;
// Connect to server
hConnect = WinHttpConnect(hSession, url.toStdWString().c_str(), INTERNET_DEFAULT_HTTP_PORT, 0);
if (!hConnect)
goto cleanup;
// Open request
hRequest = WinHttpOpenRequest(hConnect, L"GET", url.right(url.size() - url.lastIndexOf("/") - 1).toStdWString().c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hRequest)
goto cleanup;
// Send request
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
goto cleanup;
// Receive response
if (!WinHttpReceiveResponse(hRequest, NULL))
goto cleanup;
// Read response
DWORD dwSize = 0;
do {
char buffer[1024];
if (!WinHttpReadData(hRequest, buffer, sizeof(buffer), &dwSize))
goto cleanup;
result.append(buffer, dwSize);
} while (dwSize > 0);
cleanup:
if (hRequest)
WinHttpCloseHandle(hRequest);
if (hConnect)
WinHttpCloseHandle(hConnect);
if (hSession)
WinHttpCloseHandle(hSession);
return result;
}
```
这段代码使用WinHTTP库实现了一个简单的GET请求,将返回的数据存储在QByteArray中并返回。你可以将url传入函数中,函数将返回请求到的数据。
阅读全文