qt5.6使用winhttp库post https方法
时间: 2024-03-10 21:46:42 浏览: 169
QT使用https通信
如果您想直接使用WinHttp库发送HTTP POST请求,可以使用以下代码:
```cpp
#include <QtCore/QCoreApplication>
#include <Windows.h>
#include <Winhttp.h>
#include <QDebug>
#pragma comment(lib, "Winhttp.lib")
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
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;
}
HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if(!hConnect) {
qDebug() << "WinHttpConnect failed:" << GetLastError();
WinHttpCloseHandle(hSession);
return 1;
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if(!hRequest) {
qDebug() << "WinHttpOpenRequest failed:" << GetLastError();
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
LPCWSTR headers = L"Content-Type: application/x-www-form-urlencoded\r\n";
LPCWSTR data = L"key1=value1&key2=value2";
DWORD dataLength = wcslen(data) * sizeof(WCHAR);
BOOL bResult = WinHttpSendRequest(hRequest, headers, wcslen(headers), (LPVOID)data, dataLength, dataLength, 0);
if(!bResult) {
qDebug() << "WinHttpSendRequest failed:" << GetLastError();
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
bResult = WinHttpReceiveResponse(hRequest, NULL);
if(!bResult) {
qDebug() << "WinHttpReceiveResponse failed:" << GetLastError();
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
DWORD statusCode = 0;
DWORD statusCodeSize = sizeof(DWORD);
bResult = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &statusCode, &statusCodeSize, NULL);
if(!bResult) {
qDebug() << "WinHttpQueryHeaders failed:" << GetLastError();
} else {
qDebug() << "Status code:" << statusCode;
}
QByteArray responseData;
DWORD bytesRead = 0;
DWORD bufferSize = 4096;
LPBYTE buffer = new BYTE[bufferSize];
阅读全文