文件下载片段程序

CString pURL;
CString SaveAsFilePath;
pURL="http://192.168.34.18/IM.rar";
SaveAsFilePath="f:\\IM.rar";
CInternetSession session; //会话期对象)

CHttpConnection* pServer = NULL; // 指向服务器地址(URL)
CHttpFile * pHttpFile = NULL;//HTTP文件指针
CString strServerName; //服务器名
CString strObject; //查询对象名(http文件)
INTERNET_PORT nPort; //端口
DWORD dwServiceType; //服务类型
DWORD dwHttpRequestFlags = 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 && (dwServiceType ==INTERNET_SERVICE_HTTP);
if (!OK) 
{ 
    AfxMessageBox("URL出错"); //报错
    return;
}
pServer = session.GetHttpConnection(strServerName, nPort,"sys,"111"); //获得服务器名
                                    pHttpFile = pServer-> OpenRequest( CHttpConnection::HTTP_VERB_GET,strObject, NULL, 1, NULL,  NULL,dwHttpRequestFlags);//向服务器发送请求,建立http连接,
pHttpFile->AddRequestHeaders(szHeaders);//建立本机上的http文件指针
pHttpFile->SendRequest(); //发送请求
CFile f; //输出文件对象
//打开输出文件
if( !f.Open(SaveAsFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary))
{
    MessageBox("Unable to open file");
    return;
}

//下面将检索结果保存到文件上
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();
AfxMessageBox("文件下载成功!");
return;
原文地址:https://www.cnblogs.com/shengshuai/p/filedownload.html