qt 使用 winhttp demo
时间: 2023-09-16 14:14:47 浏览: 93
以下是使用 WinHTTP 在 Qt 中进行 HTTP 请求的示例代码:
```cpp
#include <QCoreApplication>
#include <QUrl>
#include <QDebug>
#include <QByteArray>
#include <Windows.h>
#include <winhttp.h>
#pragma comment(lib,"winhttp.lib")
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建 WinHTTP 会话
HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession)
{
qDebug() << "WinHttpOpen failed: " << GetLastError();
return -1;
}
// 创建 HTTP 连接
QUrl url("http://www.example.com");
HINTERNET hConnect = WinHttpConnect(hSession, reinterpret_cast<const wchar_t*>(url.host().utf16()), url.port() == -1 ? INTERNET_DEFAULT_HTTP_PORT : url.port(), 0);
if (!hConnect)
{
WinHttpCloseHandle(hSession);
qDebug() << "WinHttpConnect failed: " << GetLastError();
return -1;
}
// 创建 HTTP 请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", reinterpret_cast<const wchar_t*>(url.path().utf16()), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
if (!hRequest)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
qDebug() << "WinHttpOpenRequest failed: " << GetLastError();
return -1;
}
// 发送 HTTP 请求
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
qDebug() << "WinHttpSendRequest failed: " << GetLastError();
return -1;
}
// 等待响应
if (!WinHttpReceiveResponse(hRequest, 0))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
qDebug() << "WinHttpReceiveResponse failed: " << GetLastError();
return -1;
}
// 读取响应数据
QByteArray responseData;
DWORD dwSize = 0;
do
{
char szData[1024] = { 0 };
if (!WinHttpReadData(hRequest, szData, sizeof(szData) - 1, &dwSize))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
qDebug() << "WinHttpReadData failed: " << GetLastError();
return -1;
}
responseData.append(szData, static_cast<int>(dwSize));
} while (dwSize > 0);
// 输出响应数据
qDebug() << responseData;
// 关闭 WinHTTP 相关句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return a.exec();
}
```
在这个示例中,我们使用 WinHTTP 创建了一个 HTTP 会话、连接和请求,并发送了一个 GET 请求以获取 http://www.example.com 的响应数据。请注意,这个示例并没有处理任何错误或异常情况,你需要根据你的实际需求进行扩展和改进。
阅读全文