在C++中,使用WinHttp庫處理HTTP重定向的方法如下:
#include<iostream>
#include<windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
BOOL HandleRedirection(HINTERNET hRequest, LPCWSTR url) {
// 發(fā)送請求
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;
}
// 接收響應(yīng)
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (!bResults) {
std::cerr << "Error receiving response: "<< GetLastError()<< std::endl;
return FALSE;
}
// 獲取響應(yīng)狀態(tài)碼
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;
}
// 檢查是否為重定向狀態(tài)碼
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;
}
// 關(guān)閉當(dāng)前請求
WinHttpCloseHandle(hRequest);
// 遞歸處理重定向
return HandleRedirection(hRequest, redirectUrl);
}
// 非重定向狀態(tài)碼,處理響應(yīng)
// ...
return TRUE;
}
HandleRedirection
函數(shù)。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;
}
// 連接到服務(wù)器
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;
}
// 創(chuàng)建請求
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;
}
// 關(guān)閉句柄
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
這個示例展示了如何使用WinHttp庫處理HTTP重定向。請注意,這個示例僅適用于簡單的重定向場景。對于更復(fù)雜的場景,可能需要根據(jù)實(shí)際需求進(jìn)行相應(yīng)的修改。