帮我写个使用winhttpApi访问http://www.baidu.com的c++例子 并计算请求时间
时间: 2023-08-16 07:07:00 浏览: 167
好的,以下是一个使用WinHTTP API访问百度并计算请求时间的C++示例代码:
```cpp
#include <Windows.h>
#include <Winhttp.h>
#include <iostream>
#pragma comment(lib, "Winhttp.lib")
int main()
{
// 初始化WinHTTP库
HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession)
{
std::cerr << "Failed to open WinHTTP session: " << GetLastError() << std::endl;
return 1;
}
// 打开连接
HINTERNET hConnect = WinHttpConnect(hSession, L"www.baidu.com", INTERNET_DEFAULT_HTTP_PORT, 0);
if (!hConnect)
{
std::cerr << "Failed to connect: " << GetLastError() << std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
// 打开请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hRequest)
{
std::cerr << "Failed to open request: " << GetLastError() << 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 << "Failed to send request: " << GetLastError() << std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 等待响应
if (!WinHttpReceiveResponse(hRequest, NULL))
{
std::cerr << "Failed to receive response: " << GetLastError() << std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 获取响应时间
DWORD dwStartTime = GetTickCount();
DWORD dwEndTime;
DWORD dwBytesRead;
BYTE pBuffer[1024];
while (WinHttpReadData(hRequest, pBuffer, sizeof(pBuffer), &dwBytesRead))
{
// 读取响应内容,这里不需要处理
}
dwEndTime = GetTickCount();
// 输出请求时间
std::cout << "Request time: " << (dwEndTime - dwStartTime) << "ms" << std::endl;
// 关闭句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
```
该示例使用了WinHTTP API来访问百度首页,并计算了请求时间。具体实现步骤为:
1. 初始化WinHTTP库
2. 打开连接
3. 打开请求
4. 发送请求
5. 等待响应
6. 获取响应时间
7. 关闭句柄
注意,由于WinHTTP API是异步的,所以在等待响应时需要使用循环读取响应内容,直到读取完毕为止。在本示例中,我们使用了简单的循环来读取响应内容,但实际应用中应该根据需要进行更加完善的处理。
阅读全文