使用WinINet實現HTTP訪問:
#include <wininet.h>
InternetOpen
函數創建一個會話句柄。HINTERNET hInternet = InternetOpen(L"MyApp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hInternet == NULL) {
// 處理錯誤
return;
}
InternetOpenUrl
函數打開一個HTTP連接。HINTERNET hConnect = InternetOpenUrl(hInternet, L"http://www.example.com", NULL, 0, INTERNET_FLAG_RELOAD, 0);
if (hConnect == NULL) {
// 處理錯誤
InternetCloseHandle(hInternet);
return;
}
InternetReadFile
函數讀取HTTP響應內容。char buffer[4096];
DWORD bytesRead;
while (InternetReadFile(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
// 處理讀取的數據
// ...
}
InternetCloseHandle
函數關閉HTTP連接和會話。InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
使用WinHTTP實現HTTP訪問:
#include <winhttp.h>
WinHttpOpen
函數創建一個會話句柄。HINTERNET hSession = WinHttpOpen(L"MyApp", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (hSession == NULL) {
// 處理錯誤
return;
}
WinHttpOpenRequest
和WinHttpSendRequest
函數打開一個HTTP連接,并發送請求。HINTERNET hConnect = WinHttpOpenRequest(hSession, L"GET", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (hConnect == NULL) {
// 處理錯誤
WinHttpCloseHandle(hSession);
return;
}
if (!WinHttpSendRequest(hConnect, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
// 處理錯誤
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return;
}
WinHttpReadData
函數讀取HTTP響應內容。char buffer[4096];
DWORD bytesRead;
while (WinHttpReadData(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
// 處理讀取的數據
// ...
}
WinHttpCloseHandle
函數關閉HTTP連接和會話。WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);