利用 MFC WinInet 類別 (CInternetSession、CInternetFile) 直接開啟 HTTP 會話,讀取並儲存網頁內容至本地檔案。
BOOL GetSourceHtml(CString theUrl, CString Filename) {
CInternetSession session;
CInternetFile* pFile = NULL;
try {
pFile = (CInternetFile*)session.OpenURL(theUrl); // 連接 URL
} catch (CInternetException* pEx) {
pEx->Delete();
return FALSE;
}
CStdioFile dataStore;
CString strPath = GetAppPath(); // 取得應用程式目錄
if (pFile) {
if (!dataStore.Open(strPath + "\\" + Filename,
CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText))
return FALSE;
CString strLine;
while (pFile->ReadString(strLine)) { // 逐行讀取
dataStore.WriteString(strLine);
dataStore.WriteString("\n"); // 保留換行
}
pFile->Close();
delete pFile;
} else {
dataStore.WriteString(_T("連接伺服器失敗..."));
return FALSE;
}
return TRUE;
}
// 取得應用程式目錄
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, MAX_PATH);
CString strPath(szPath);
int nPos = strPath.ReverseFind('\\');
strPath = strPath.Left(nPos);
// 下載並儲存
BOOL bSuccess = GetSourceHtml(_T("https://www.example.com"), _T("Page.html"));
#include <afxinet.h> 引入 WinInet 標頭。| 類別 | 用途 |
|---|---|
| CInternetSession | 管理網際網路會話,支援 HTTP/FTP/Gopher |
| CInternetFile | 網路檔案抽象,提供 ReadString/WriteString 等介面 |
| CStdioFile | 本地文字檔案操作,配合 CFile 模式旗標 |
注意: CInternetFile::ReadString 會移除換行符,寫入時需手動補回 \n。若需保留原始二進制內容,改用 Read/Write 並設定 CFile::typeBinary。