要使用C++和WinHttp库实现HTTPS请求,请按照以下步骤操作:
-
首先,确保已经安装了Windows SDK,因为它包含了WinHttp库。
-
在你的C++项目中,包含必要的头文件:
#include#include #include #pragma comment(lib, "winhttp")
- 编写一个函数来发送HTTPS请求:
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; }
- 编译并运行程序。它将发送一个HTTPS GET请求到指定的URL,并输出响应内容。
注意:这个示例仅用于演示目的。在实际项目中,你可能需要处理更多的错误情况,例如内存分配失败、无效的URL等。此外,你还可以根据需要添加其他功能,例如设置请求头、发送POST请求等。