@omg-two
2016-10-18T06:45:09.000000Z
字数 1058
阅读 744
C++
MFC
在MFC环境下,访问网页,并将抓取的网页保存到本地。
加入头文件:
#include <afxinet.h>
MFC下代码示例:
CString strSentence, strWriteName = _T("test.php");
CString strFileName ;
strFileName.Format(_T("%s%s%s"),_T("http://localhost/CEA/admin/"), strWriteName,_T("?name=fzj"));
CInternetSession sess;
CHttpFile* fileGet;
try
{
fileGet = (CHttpFile*)sess.OpenURL(strFileName);
}
catch (CException* e)
{
fileGet = 0;
throw;
}
if (fileGet)
{
DWORD dwStatus;
DWORD dwBuffLen = sizeof(dwStatus);
BOOL bSuccess = fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);
if (bSuccess && dwStatus >= 200 && dwStatus<300)
{
CStdioFile fileWrite;
if (fileWrite.Open(strWriteName, CFile::modeWrite | CFile::modeCreate))
{
while (fileGet->ReadString(strSentence))
{
fileWrite.WriteString(strSentence + "\n");
}
fileWrite.Close();
AfxMessageBox(_T("下载完毕"));
}
else
{
AfxMessageBox(_T("本地文件") + strWriteName + _T("打开出错."));
}
}
else
{
strSentence.Format(_T("打开网页文件出错,错误码:%d"), dwStatus);
AfxMessageBox(strSentence);
}
fileGet->Close();
delete fileGet;
}
else
AfxMessageBox(_T("不能找到网页文件!"));
sess.Close();
当url字符串设置出问题,比如没有加入http://等情况,会出现报错:“URL未识别的协议”。