阅读量:1
使用WinINet实现HTTP访问:
- 包含头文件:
#include <wininet.h>
- 初始化WinINet:调用
InternetOpen
函数创建一个会话句柄。HINTERNET hInternet = InternetOpen(L"MyApp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (hInternet == NULL) { // 处理错误 return; }
- 打开HTTP连接:调用
InternetOpenUrl
函数打开一个HTTP连接。HINTERNET hConnect = InternetOpenUrl(hInternet, L"http://www.example.com", NULL, 0, INTERNET_FLAG_RELOAD, 0); if (hConnect == NULL) { // 处理错误 InternetCloseHandle(hInternet); return; }
- 读取HTTP响应:使用
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>
- 初始化WinHTTP:调用
WinHttpOpen
函数创建一个会话句柄。HINTERNET hSession = WinHttpOpen(L"MyApp", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) { // 处理错误 return; }
- 打开HTTP连接:调用
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; }
- 读取HTTP响应:使用
WinHttpReadData
函数读取HTTP响应内容。char buffer[4096]; DWORD bytesRead; while (WinHttpReadData(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) { // 处理读取的数据 // ... }
- 关闭连接和会话:调用
WinHttpCloseHandle
函数关闭HTTP连接和会话。WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession);