首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

MFC 使用 WinInet 下載並儲存網頁原始碼

     編輯:關於C語言

利用 MFC WinInet 類別 (CInternetSession、CInternetFile) 直接開啟 HTTP 會話,讀取並儲存網頁內容至本地檔案。

核心函式:GetSourceHtml

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"));

必要設定

  1. 專案屬性 → C/C++ → 預處理器 → 加入 _AFXDLL (若非共享 MFC)。
  2. #include <afxinet.h> 引入 WinInet 標頭。
  3. 連結庫:wininet.lib (通常自動連結)。

關鍵類別說明

類別用途
CInternetSession管理網際網路會話,支援 HTTP/FTP/Gopher
CInternetFile網路檔案抽象,提供 ReadString/WriteString 等介面
CStdioFile本地文字檔案操作,配合 CFile 模式旗標
注意: CInternetFile::ReadString 會移除換行符,寫入時需手動補回 \n。若需保留原始二進制內容,改用 Read/Write 並設定 CFile::typeBinary。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved