使用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);