在 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 請求,然后輸出響應頭。注意,你需要根據實際情況修改服務器地址和請求路徑。