解决CInternetSession运行异常的问题

来源:互联网 发布:各个协议的端口号列表 编辑:程序博客网 时间:2024/06/05 13:24

最近在做一个小任务,其中有一项功能是获取网页源码,VC中可以用CInternetSession来实现,以下为从MSDN摘下来的
CInternetSession session;
CHttpFile* file = NULL;

file = (CHttpFile *)session.OpenURL(_T("http://www.microsoft.com"));
if (NULL != file)
{
//Do something here with the web request

//Clean up the file here to avoid a memory leak!!!!!!!
file->Close();
delete file;
}
session.Close();

把上面的程序片断加到一个win32程序里,加上#include <afxinet.h>和一些必要的头文件,把项目属性->使用MFC改为“Use MFC in a Shared DLL”
可以编译通过,但在运行总是会出现异常,报告的错误为:
afxwin1.inl
Line: 29

调试跟踪到说AfxCurrentAppName为空。解决办法:
CWinApp app((LPCTSTR)argv[0]);
app.InitApplication();
AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);

分析:在win32程序中调用MFC中的类,需要初始化(这里写得模糊点,因为目前对MFC实在是一窍不通)。

#include <stdio.h>
#include <afxinet.h>
#include <afx.h>
#include <afxwin.h>

int main(int argc, char **argv)
{
    CWinApp app((LPCTSTR)argv[0]);
    app.InitApplication();
    AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
    CInternetSession session;
    CHttpFile* file = NULL;

    file = (CHttpFile *)session.OpenURL(_T("http://www.microsoft.com"));
    if (NULL != file)
    {
        //Do something here with the web request
        //Clean up the file here to avoid a memory leak!!!!!!!
        file->Close();
        delete file;
    }
    session.Close();
    return 0;
}

ps:我遇到的问题,问了同事,在他的帮助下解决的,哈哈

原创粉丝点击