使用WinINet和WinHTTP实现Http访问

avatar
作者
猴君
阅读量:7

使用WinINet实现Http访问:

#include <windows.h> #include <wininet.h> #include <iostream>  int main() {     HINTERNET hInternet;     HINTERNET hConnect;     DWORD bytesRead;     char buffer[4096];      // 初始化WinINet     hInternet = InternetOpen(L"WinINet Example", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);     if (hInternet == NULL) {         std::cout << "Failed to initialize WinINet: " << GetLastError() << std::endl;         return 1;     }          // 打开Http连接     hConnect = InternetOpenUrlA(hInternet, "http://www.example.com", NULL, 0, INTERNET_FLAG_RELOAD, 0);     if (hConnect == NULL) {         std::cout << "Failed to open Http connection: " << GetLastError() << std::endl;         return 1;     }          // 读取响应数据     while (InternetReadFile(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {         std::cout.write(buffer, bytesRead);     }          // 关闭连接和WinINet     InternetCloseHandle(hConnect);     InternetCloseHandle(hInternet);          return 0; }  

使用WinHTTP实现Http访问:

#include <windows.h> #include <winhttp.h> #include <iostream>  int main() {     HINTERNET hSession;     HINTERNET hConnect;     DWORD bytesRead;     char buffer[4096];      // 初始化WinHTTP     hSession = WinHttpOpen(L"WinHTTP Example", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);     if (hSession == NULL) {         std::cout << "Failed to initialize WinHTTP: " << GetLastError() << std::endl;         return 1;     }      // 打开Http连接     hConnect = WinHttpOpenRequest(hSession, L"GET", L"http://www.example.com", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);     if (hConnect == NULL) {         std::cout << "Failed to open Http connection: " << GetLastError() << std::endl;         WinHttpCloseHandle(hSession);         return 1;     }      // 发送请求     if (!WinHttpSendRequest(hConnect, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {         std::cout << "Failed to send Http request: " << GetLastError() << std::endl;         WinHttpCloseHandle(hConnect);         WinHttpCloseHandle(hSession);         return 1;     }      // 接收响应     if (!WinHttpReceiveResponse(hConnect, NULL)) {         std::cout << "Failed to receive Http response: " << GetLastError() << std::endl;         WinHttpCloseHandle(hConnect);         WinHttpCloseHandle(hSession);         return 1;     }      // 读取响应数据     while (WinHttpReadData(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {         std::cout.write(buffer, bytesRead);     }      // 关闭连接和WinHTTP     WinHttpCloseHandle(hConnect);     WinHttpCloseHandle(hSession);      return 0; } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!