在C++中,使用WinHttp庫處理HTTP重定向的方法如下:
#include<iostream>
#include<windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
BOOL HandleRedirection(HINTERNET hRequest, LPCWSTR url) {
// 發送請求
BOOL bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
if (!bResults) {
std::cerr << "Error sending request: "<< GetLastError()<< std::endl;
return FALSE;
}
// 接收響應
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (!bResults) {
std::cerr << "Error receiving response: "<< GetLastError()<< std::endl;
return FALSE;
}
// 獲取響應狀態碼
DWORD dwStatusCode = 0;
DWORD dwSize = sizeof(dwStatusCode);
bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwStatusCode, &dwSize, NULL);
if (!bResults) {
std::cerr << "Error querying headers: "<< GetLastError()<< std::endl;
return FALSE;
}
// 檢查是否為重定向狀態碼
if (dwStatusCode >= 300 && dwStatusCode < 400) {
// 獲取重定向URL
WCHAR redirectUrl[2048];
DWORD redirectUrlSize = sizeof(redirectUrl);
bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_LOCATION, NULL, redirectUrl, &redirectUrlSize, NULL);
if (!bResults) {
std::cerr << "Error querying location header: "<< GetLastError()<< std::endl;
return FALSE;
}
// 關閉當前請求
WinHttpCloseHandle(hRequest);
// 遞歸處理重定向
return HandleRedirection(hRequest, redirectUrl);
}
// 非重定向狀態碼,處理響應
// ...
return TRUE;
}
HandleRedirection
函數。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 opening session: "<< GetLastError()<< std::endl;
return 1;
}
// 連接到服務器
HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
std::cerr << "Error connecting to server: "<< GetLastError()<< 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 opening request: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 處理重定向
BOOL bResults = HandleRedirection(hRequest, L"https://example.com/path/to/resource");
if (!bResults) {
std::cerr << "Error handling redirection: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 關閉句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
這個示例展示了如何使用WinHttp庫處理HTTP重定向。請注意,這個示例僅適用于簡單的重定向場景。對于更復雜的場景,可能需要根據實際需求進行相應的修改。