在C++中,使用WinHttp库进行HTTP请求时,可以通过设置WINHTTP_OPTION_CONNECT_TIMEOUT
和WINHTTP_OPTION_RECEIVE_TIMEOUT
选项来控制连接超时和接收数据超时。
以下是一个简单的示例,展示了如何设置这些超时选项:
#include<iostream>
#include<Windows.h>
#include <winhttp.h>
int main() {
// 初始化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: WinHttpOpen failed."<< std::endl;
return 1;
}
// 设置连接超时(毫秒)
DWORD connectTimeout = 5000; // 5 seconds
if (!WinHttpSetOption(hSession, WINHTTP_OPTION_CONNECT_TIMEOUT, &connectTimeout, sizeof(connectTimeout))) {
std::cerr << "Error: WinHttpSetOption (WINHTTP_OPTION_CONNECT_TIMEOUT) failed."<< std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
// 设置接收数据超时(毫秒)
DWORD receiveTimeout = 10000; // 10 seconds
if (!WinHttpSetOption(hSession, WINHTTP_OPTION_RECEIVE_TIMEOUT, &receiveTimeout, sizeof(receiveTimeout))) {
std::cerr << "Error: WinHttpSetOption (WINHTTP_OPTION_RECEIVE_TIMEOUT) failed."<< std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
// 创建连接
HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
std::cerr << "Error: WinHttpConnect failed."<< std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
// 创建请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/path/to/resource", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
std::cerr << "Error: WinHttpOpenRequest failed."<< std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 发送请求
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
std::cerr << "Error: WinHttpSendRequest failed."<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 接收响应
if (!WinHttpReceiveResponse(hRequest, NULL)) {
std::cerr << "Error: WinHttpReceiveResponse failed."<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 处理响应...
// 清理资源
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
在这个示例中,我们首先使用WinHttpOpen
函数初始化一个WinHttp会话。然后,我们使用WinHttpSetOption
函数设置连接超时和接收数据超时。接下来,我们创建一个连接并打开一个请求,然后发送请求并接收响应。最后,我们关闭所有打开的句柄并返回。
注意:在实际应用程序中,你可能需要根据需要调整超时值。