在 C++ 中,使用 WinHTTP 库处理 HTTP 响应头的方法如下:
winhttp.lib
库。#include<iostream>
#include<windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
使用 WinHttpOpen()
、WinHttpConnect()
和 WinHttpOpenRequest()
函数初始化 HTTP 请求。
使用 WinHttpSendRequest()
函数发送 HTTP 请求。
使用 WinHttpReceiveResponse()
函数接收 HTTP 响应。
使用 WinHttpQueryHeaders()
函数查询和处理响应头。
以下是一个完整的示例代码:
#include<iostream>
#include<windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
int main() {
// 初始化 HTTP 会话
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 HTTP session."<< std::endl;
return -1;
}
// 连接到服务器
HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
std::cerr << "Error connecting to server."<< std::endl;
WinHttpCloseHandle(hSession);
return -1;
}
// 打开 HTTP 请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/path", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
std::cerr << "Error opening request."<< std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return -1;
}
// 发送 HTTP 请求
BOOL bResult = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
if (!bResult) {
std::cerr << "Error sending request."<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return -1;
}
// 接收 HTTP 响应
bResult = WinHttpReceiveResponse(hRequest, NULL);
if (!bResult) {
std::cerr << "Error receiving response."<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return -1;
}
// 查询和处理响应头
DWORD dwSize = 0;
WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, NULL, &dwSize, WINHTTP_NO_HEADER_INDEX);
std::wstring headers(dwSize / sizeof(wchar_t), L'\0');
bResult = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, &headers[0], &dwSize, WINHTTP_NO_HEADER_INDEX);
if (!bResult) {
std::cerr << "Error querying headers."<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return -1;
}
std::wcout << L"Response headers:"<< std::endl<< headers<< std::endl;
// 关闭句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
这个示例代码将连接到 example.com
服务器,发送一个 GET 请求,然后输出响应头。注意,你需要根据实际情况修改服务器地址和请求路径。