要使用C++和WinHttp庫實現HTTPS請求,請按照以下步驟操作:
首先,確保已經安裝了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;
}
// 發送請求
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;
}
// 讀取響應內容
DWORD dwSize = 0;
do {
DWORD dwDownloaded = 0;
char* pszOutBuffer;
do {
// 分配空間以存儲響應數據
dwSize += 1024;
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer) {
std::cerr << "Out of memory"<< std::endl;
break;
}
// 查詢可用數據量
bResults = WinHttpQueryDataAvailable(hRequest, &dwDownloaded);
if (!bResults) {
delete[] pszOutBuffer;
std::cerr << "Error querying data available: "<< GetLastError()<< std::endl;
break;
}
// 讀取數據
ZeroMemory(pszOutBuffer, dwSize + 1);
bResults = WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwDownloaded, &dwDownloaded);
if (!bResults) {
delete[] pszOutBuffer;
std::cerr << "Error reading data: "<< GetLastError()<< std::endl;
break;
}
// 輸出數據
std::cout << pszOutBuffer;
// 釋放內存
delete[] pszOutBuffer;
} while (dwDownloaded > 0);
} while (dwDownloaded > 0);
// 關閉句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
}
int main() {
SendHttpsRequest(L"example.com");
return 0;
}
注意:這個示例僅用于演示目的。在實際項目中,你可能需要處理更多的錯誤情況,例如內存分配失敗、無效的URL等。此外,你還可以根據需要添加其他功能,例如設置請求頭、發送POST請求等。