要使用C++和WinHttp庫實現(xiàn)HTTPS請求,請按照以下步驟操作:
首先,確保已經(jīng)安裝了Windows SDK,因為它包含了WinHttp庫。
在你的C++項目中,包含必要的頭文件:
#include<iostream>
#include<windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp")
void SendHttpsRequest(const std::wstring& url) {
// 打開WinHttp會話
HINTERNET hSession = WinHttpOpen(L"MyUserAgent", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) {
std::cerr << "Error opening session: "<< GetLastError()<< std::endl;
return;
}
// 連接到服務器
HINTERNET hConnect = WinHttpConnect(hSession, url.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
std::cerr << "Error connecting to server: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hSession);
return;
}
// 打開請求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", nullptr, nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
std::cerr << "Error opening request: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return;
}
// 發(fā)送請求
BOOL bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
if (!bResults) {
std::cerr << "Error sending request: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return;
}
// 接收響應
bResults = WinHttpReceiveResponse(hRequest, nullptr);
if (!bResults) {
std::cerr << "Error receiving response: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return;
}
// 讀取響應內(nèi)容
DWORD dwSize = 0;
do {
DWORD dwDownloaded = 0;
char* pszOutBuffer;
do {
// 分配空間以存儲響應數(shù)據(jù)
dwSize += 1024;
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer) {
std::cerr << "Out of memory"<< std::endl;
break;
}
// 查詢可用數(shù)據(jù)量
bResults = WinHttpQueryDataAvailable(hRequest, &dwDownloaded);
if (!bResults) {
delete[] pszOutBuffer;
std::cerr << "Error querying data available: "<< GetLastError()<< std::endl;
break;
}
// 讀取數(shù)據(jù)
ZeroMemory(pszOutBuffer, dwSize + 1);
bResults = WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwDownloaded, &dwDownloaded);
if (!bResults) {
delete[] pszOutBuffer;
std::cerr << "Error reading data: "<< GetLastError()<< std::endl;
break;
}
// 輸出數(shù)據(jù)
std::cout << pszOutBuffer;
// 釋放內(nèi)存
delete[] pszOutBuffer;
} while (dwDownloaded > 0);
} while (dwDownloaded > 0);
// 關(guān)閉句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
}
int main() {
SendHttpsRequest(L"example.com");
return 0;
}
注意:這個示例僅用于演示目的。在實際項目中,你可能需要處理更多的錯誤情況,例如內(nèi)存分配失敗、無效的URL等。此外,你還可以根據(jù)需要添加其他功能,例如設(shè)置請求頭、發(fā)送POST請求等。