核心函數:GetSourceHtml
BOOL GetSourceHtml(CString theUrl, CString Filename) {
CInternetSession session;
CInternetFile* file = NULL;
try {
file = (CInternetFile*)session.OpenURL(theUrl);
}
catch (CInternetException* e) {
file = NULL;
e->Delete();
return FALSE;
}
CStdioFile dataStore;
if (file) {
CString line;
BOOL bOk = dataStore.Open(strPath + "\\" + Filename,
CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText);
if (!bOk) return FALSE;
while (file->ReadString(line) != NULL) {
dataStore.WriteString(line);
dataStore.WriteString("\n"); // ReadString 會移除換行,需補回
}
file->Close();
delete file;
}
else {
dataStore.WriteString(_T("連線失敗..."));
return FALSE;
}
return TRUE;
}
使用步驟
- 包含標頭:
#include "afxinet.h"
- 專案設定:連結
wininet.lib(MFC 專案通常自動處理)。
- 取得模組路徑作為儲存基準:
GetModuleFileName(NULL, strPath.GetBufferSetLength(MAX_PATH+1), MAX_PATH);
strPath.ReleaseBuffer();
int nPos = strPath.ReverseFind('\\');
strPath = strPath.Left(nPos);
呼叫範例
BOOL m_bDownloadFailed;
m_bDownloadFailed = GetSourceHtml(_T("https://www.example.com"), _T("News.txt"));
關鍵技術細節
- 例外處理:
OpenURL 可能拋出 CInternetException,必須 catch 並呼叫 Delete() 釋放例外物件。
- 文字模式儲存:
CFile::typeText 會自動將 \n 轉為 \r\n(Windows 換行)。若需保留原始二進位內容(如圖片、二進位檔),移除 typeText 改用 CFile::typeBinary,並用 Read/Write 處理原始位元組。
- 緩衝區大小:
ReadString 內部緩衝有限,超長行可能截斷。大檔案建議改用 Read 固定大小塊讀寫。
- 非同步/進度顯示:
CInternetSession 支援回呼 SetStatusCallback 實作進度列、取消下載。
- Proxy 支援:
CInternetSession 建構函數可指定 Proxy 伺服器與認證。
擴充應用
- 批次下載:迴圈呼叫,搭配執行緒池平行化。
- 斷點續傳:HTTP Range 標頭 +
CFile::modeNoTruncate 追加寫入。
- HTTPS:WinInet 原生支援,僅需 URL 為
https://。
- 表單提交:
OpenURL 以 POST 方法傳送資料(需設定 INTERNET_FLAG_FORMS_SUBMIT)。