[关闭]
@omg-two 2016-10-18T06:45:09.000000Z 字数 1058 阅读 744

C++访问网页

C++ MFC


问题描述

在MFC环境下,访问网页,并将抓取的网页保存到本地。

解决方案

加入头文件:

  1. #include <afxinet.h>

MFC下代码示例:

  1. CString strSentence, strWriteName = _T("test.php");
  2. CString strFileName ;
  3. strFileName.Format(_T("%s%s%s"),_T("http://localhost/CEA/admin/"), strWriteName,_T("?name=fzj"));
  4. CInternetSession sess;
  5. CHttpFile* fileGet;
  6. try
  7. {
  8. fileGet = (CHttpFile*)sess.OpenURL(strFileName);
  9. }
  10. catch (CException* e)
  11. {
  12. fileGet = 0;
  13. throw;
  14. }
  15. if (fileGet)
  16. {
  17. DWORD dwStatus;
  18. DWORD dwBuffLen = sizeof(dwStatus);
  19. BOOL bSuccess = fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);
  20. if (bSuccess && dwStatus >= 200 && dwStatus<300)
  21. {
  22. CStdioFile fileWrite;
  23. if (fileWrite.Open(strWriteName, CFile::modeWrite | CFile::modeCreate))
  24. {
  25. while (fileGet->ReadString(strSentence))
  26. {
  27. fileWrite.WriteString(strSentence + "\n");
  28. }
  29. fileWrite.Close();
  30. AfxMessageBox(_T("下载完毕"));
  31. }
  32. else
  33. {
  34. AfxMessageBox(_T("本地文件") + strWriteName + _T("打开出错."));
  35. }
  36. }
  37. else
  38. {
  39. strSentence.Format(_T("打开网页文件出错,错误码:%d"), dwStatus);
  40. AfxMessageBox(strSentence);
  41. }
  42. fileGet->Close();
  43. delete fileGet;
  44. }
  45. else
  46. AfxMessageBox(_T("不能找到网页文件!"));
  47. sess.Close();

注意事项

当url字符串设置出问题,比如没有加入http://等情况,会出现报错:“URL未识别的协议”。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注