从WEB服务器下载文件的简单方法。

    技术2022-05-11  44

    只需一个函数就可以实现了,首先要包含头文件afxinet.h

    以下是所需代码。

    BOOL CDownLoadDlg::GetFromWeb(LPSTR pURL, LPSTR SaveAsFilePath){CInternetSession session; //会话期对象)

    CHttpConnection* pServer = NULL; // 指向服务器地址(URL)

    CHttpFile * pHttpFile = NULL;//HTTP文件指针

    CString strServerName; //服务器名

    CString strObject; //查询对象名(http文件)

    INTERNET_PORT nPort; //端口

    DWORD dwServiceType; //服务类型

    DWORD dwHttpRequestFlags = //请求标志

    //INTERNET_FLAG_EXISTING_CONNECT;

    INTERNET_FLAG_NO_AUTO_REDIRECT;

    const TCHAR szHeaders[]=_T("Accept: text/*/r/nUser-Agent:HttpClient/r/n");

    BOOL OK=AfxParseURL( //词法分析

    pURL, //被分析URL串

    dwServiceType, //服务类型,ftp,http等

    strServerName, //服务器名

    strObject, //URL中被查询对象

    nPort ); //URL指定的端口,可能为空

    OK=OK && //本例只考虑http协议

    (dwServiceType ==

    INTERNET_SERVICE_HTTP);

    if (!OK)

    { AfxMessageBox("URL出错"); //报错

    return false;

    }

    pServer = session.GetHttpConnection(strServerName, nPort); //获得服务器名

    pHttpFile = pServer-> OpenRequest( CHttpConnection::HTTP_VERB_GET,strObject, NULL, 1, NULL, NULL,dwHttpRequestFlags);

    //向服务器发送请求,建立http连接,

    //建立本机上的http文件指针

    pHttpFile->AddRequestHeaders(szHeaders);

    pHttpFile->SendRequest(); //发送请求

    CStdioFile f; //输出文件对象

    if( !f.Open( //打开输出文件

    SaveAsFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary ) )

    { MessageBox("Unable to open file");

    return false;

    }

    //下面将检索结果保存到文件上

    TCHAR szBuf[1024]; //缓存int length=0;long a=pHttpFile->GetLength();while (length=pHttpFile->Read(szBuf, 1023))

    f.Write(szBuf,length);

    f.Close(); //善后工作

    pHttpFile ->Close();

    pServer ->Close();

    if (pHttpFile != NULL) delete pHttpFile;

    if (pServer != NULL) delete pServer;

    session.Close();

    return true;

    }


    最新回复(0)