写一个c++ http请求程序
时间: 2023-11-29 15:05:27 浏览: 88
以下是一个简单的 C++ HTTP 请求程序示例,使用 WinHTTP 库发送 GET 请求。本示例仅供参考,实际使用中可能需要根据具体情况进行修改和调整。
```c++
#include <iostream>
#include <Windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
int main(int argc, char* argv[])
{
// 创建 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" << std::endl;
return 1;
}
// 创建 HTTP 连接
HINTERNET hConnect = WinHttpConnect(hSession, L"www.example.com", INTERNET_DEFAULT_HTTP_PORT, 0);
if (!hConnect)
{
std::cerr << "Failed to connect to server" << std::endl;
WinHttpCloseHandle(hSession);
return 2;
}
// 创建 HTTP 请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hRequest)
{
std::cerr << "Failed to create HTTP request" << std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 3;
}
// 发送 HTTP 请求
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
{
std::cerr << "Failed to send HTTP request" << std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 4;
}
// 等待响应
if (!WinHttpReceiveResponse(hRequest, NULL))
{
std::cerr << "Failed to receive HTTP response" << std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 5;
}
// 读取响应数据
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
do
{
// 确定缓冲区大小
dwSize += 4096;
pszOutBuffer = new char[dwSize];
// 读取数据
if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, 4096, &dwDownloaded))
{
std::cerr << "Failed to read HTTP response data" << std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
delete[] pszOutBuffer;
return 6;
}
else
{
// 输出数据
std::cout << pszOutBuffer;
}
// 释放缓冲区
delete[] pszOutBuffer;
} while (dwDownloaded > 0);
// 关闭请求、连接和会话句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
```
在本示例中,首先创建了 WinHTTP 会话,然后创建了 HTTP 连接和 HTTP 请求。接着,发送 HTTP 请求,并等待响应。最后,读取响应数据并输出。注意,在实际使用中,需要根据具体情况设置 HTTP 请求的方法、URL、请求头、请求数据等参数。
阅读全文