WinInet (wininet.dll) 為系統級 HTTP/FTP/Gopher 客戶端庫,整合 IE 設定(Proxy、快取、Cookie)。MFC 提供三層封裝:
CInternetSession — 管理連線設定、回呼、全域狀態。CHttpConnection、CFtpConnection、CGopherConnection — 代表與特定伺服器的會話。CHttpFile、CFtpFileFind、CInternetFile — 實際資料傳輸介面,繼承 CStdioFile 支援 ReadString/WriteString。CInternetSession 建構關鍵參數CInternetSession(LPCTSTR pstrAgent = NULL, // User-Agent,NULL 使用預設
DWORD dwContext = 1, // 非同步回呼識別碼
DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG, // 連線類型
LPCTSTR pstrProxyName = NULL, // Proxy 位址
LPCTSTR pstrProxyBypass = NULL,// Proxy 例外清單
DWORD dwFlags = 0); // 旗標
dwAccessType:PRECONFIG(用 IE 設定)、DIRECT(直連)、PROXY(指定 Proxy)。dwFlags:INTERNET_FLAG_DONT_CACHE(不快取)、INTERNET_FLAG_OFFLINE(離線模式)。CInternetSession session(_T("MyApp/1.0"));
CStdioFile* pFile = session.OpenURL(_T("https://example.com/api/data"),
1, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_RELOAD);
CString strLine, strResponse;
while (pFile->ReadString(strLine)) strResponse += strLine + _T("\n");
pFile->Close();
delete pFile;
session.Close();
// 處理 strResponse...
CInternetSession session;
CHttpConnection* pConn = session.GetHttpConnection(_T("api.example.com"), INTERNET_DEFAULT_HTTP_PORT);
CHttpFile* pFile = pConn->OpenRequest(CHttpConnection::HTTP_VERB_POST,
_T("/submit"), NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD);
pFile->AddRequestHeaders(_T("Content-Type: application/x-www-form-urlencoded"));
CString strPostData = _T("name=test&value=123");
pFile->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)strPostData, strPostData.GetLength());
CString strResp;
while (pFile->ReadString(strLine)) strResp += strLine + _T("\n");
// 清理
pFile->Close(); delete pFile;
pConn->Close(); delete pConn;
session.Close();
| 旗標 | 用途 |
|---|---|
| INTERNET_FLAG_RELOAD | 強制從伺服器重新取得,忽略快取 |
| INTERNET_FLAG_DONT_CACHE | 不將結果存入 IE 快取 |
| INTERNET_FLAG_SECURE | HTTPS 連線 |
| INTERNET_FLAG_KEEP_CONNECTION | 保持連線 (HTTP 1.1 Keep-Alive) |
| INTERNET_FLAG_NO_AUTO_REDIRECT | 禁止自動重導向,手動處理 301/302 |
dwContext,覆寫 OnStatusCallback 處理 INTERNET_STATUS_CONNECTING_TO_SERVER、INTERNET_STATUS_REQUEST_COMPLETE 等事件。CAsyncMonikerFile 配合 IBindStatusCallback 實現更精細進度控制。所有網路操作拋出 CInternetException*,捕獲後呼叫 GetErrorMessage 取得描述,m_dwError 為 WinInet 錯誤碼(如 ERROR_INTERNET_TIMEOUT、ERROR_INTERNET_NAME_NOT_RESOLVED)。