URLDownloadToFile.docx
- 文档编号:24886122
- 上传时间:2023-06-02
- 格式:DOCX
- 页数:13
- 大小:17.04KB
URLDownloadToFile.docx
《URLDownloadToFile.docx》由会员分享,可在线阅读,更多相关《URLDownloadToFile.docx(13页珍藏版)》请在冰豆网上搜索。
URLDownloadToFile
URLDownloadToFile
(获取ie之中的下载文件)c#调用URLDownloadToFile
c#调用URLDownloadToFile
usingSystem.Runtime.InteropServices;
[DllImport("urlmon.dll",CharSet=CharSet.Auto,SetLastError=true)]
publicstaticexternInt32URLDownloadToFile(
[MarshalAs(UnmanagedType.IUnknown)]objectpCaller,
[MarshalAs(UnmanagedType.LPWStr)]stringszURL,
[MarshalAs(UnmanagedType.LPWStr)]stringszFileName,
Int32dwReserved,
IntPtrlpfnCB);//下载
intiresult=URLDownloadToFile(null,sUrlYzm,sFileYzmGif,0,IntPtr.Zero);
if(iresult!
=0)
return;
URLDownloadToFile
在服务中、一般程序中利用Inet相关函数下载数据[原创]
虽然可以使用URLDownloadFileToXXX()这个API,但是,它在使用了代理的时候会遇到麻烦。
这点,Windows自动更新发生过这样的问题:
如果使用了IE代理,如果下载代码位于系统帐号
下,代理设置可能会失效。
当然,也可以为系统帐号手动设置代理(其实就是IE的代理的设置
方法),不过,程序会受到很多的限制。
所以,可以考虑使用下属两个函数进行使用-服务程序亦可。
//DownloadafilefromtheURL.
boolCHttpDownload:
:
UrlDownloadToFile(TCHAR*ptszURL,TCHAR*ptszFilePath)
{
HINTERNEThNet;
HINTERNEThFile;
std:
:
stringsProxyServer;
DWORDdwStatusCode;
TCHARdwStatusCode1[32]={0};
DWORDdwSize1=sizeof(dwStatusCode1),dwSize=sizeof(DWORD);
intnfilesize;//filesize,2GBlimited.;)
m_sUrl=ptszURL;
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()++");
//
if(m_ConnectionType==UseProxy)
{
//OutputDebugString("\n==>Useproxy");
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_PROXY,m_sProxy.c_str(),NULL,0);
}
elseif(m_ConnectionType==DirectToInternet)
{
//OutputDebugString("\n==>DirectToInternet");
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
}
elseif(m_ConnectionType==UsePreConfig)
{
//OutputDebugString("\n==>UsePreConfig");
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
}
if(hNet==NULL)
{
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.1");
returnfalse;
}
hFile=InternetOpenUrl(hNet,m_sUrl.c_str(),NULL,0,0,0);
if(hFile==NULL)
{
InternetCloseHandle(hNet);
//OutputDebugString(m_sUrl.c_str());
//OutputDebugString(ptszURL);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.2");
returnfalse;
}
BOOLbRet=HttpQueryInfo(hFile,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwSize,NULL);
if(200!
=dwStatusCode)//ifURIisnotexist,giveup.
{
InternetCloseHandle(hNet);
InternetCloseHandle(hFile);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.3");
returnfalse;
}
if(HttpQueryInfo(hFile,HTTP_QUERY_CONTENT_LENGTH,&dwStatusCode1,&dwSize1,NULL))
{
nfilesize=atoi(dwStatusCode1);//filesize.
}
HANDLEhDownFile=CreateFile(ptszFilePath,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(INVALID_HANDLE_VALUE==hDownFile)
{
InternetCloseHandle(hNet);
InternetCloseHandle(hFile);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.4");
returnfalse;
}
//O.K.savefile
DWORDdwWrite,dwBytesRead=0;
charbufFile[MAX_BUFFER_SIZE]={0};
DWORDdwSurplus=nfilesize%sizeof(bufFile);
while(true)
{
//ReadFileDataFromNet.
BOOLbRead=InternetReadFile(hFile,bufFile,sizeof(bufFile),&dwBytesRead);
if(dwBytesRead==0)//Endoffile.
break;
//Writefiledata.
WriteFile(hDownFile,bufFile,dwBytesRead,&dwWrite,NULL);
}
InternetCloseHandle(hFile);
InternetCloseHandle(hNet);
CloseHandle(hDownFile);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.");
returntrue;
}
//DownloadURLcontentstomemorybuffer.
//ifpBuf==NULL,*pdwBufSizewillcontaintherealsizeofremotesize;
//*pdwBufSizealwaylscontainsthesizeofremotesize.
boolCHttpDownload:
:
UrlDownloadToBuffer(TCHAR*ptszURL,LPVOIDpBuf,DWORD*pdwBufSize)
{
HINTERNEThNet;
HINTERNEThFile;
std:
:
stringsProxyServer;
DWORDdwStatusCode;
TCHARdwStatusCode1[32]={0};
DWORDdwSize1=sizeof(dwStatusCode1),dwSize=sizeof(DWORD);
intnfilesize;//filesize,2GBlimited.;)
m_sUrl=ptszURL;
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()++");
//
if(m_ConnectionType==UseProxy)
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_PROXY,m_sProxy.c_str(),NULL,0);
elseif(m_ConnectionType==DirectToInternet)
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
elseif(m_ConnectionType==UsePreConfig)
hNet=InternetOpen(tszAgent,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if(hNet==NULL)
{
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.1");
returnfalse;
}
hFile=InternetOpenUrl(hNet,m_sUrl.c_str(),NULL,0,0,0);
if(hFile==NULL)
{
InternetCloseHandle(hNet);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.2");
returnfalse;
}
BOOLbRet=HttpQueryInfo(hFile,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwSize,NULL);
if(200!
=dwStatusCode)//ifURIisnotexist,giveup.
{
InternetCloseHandle(hNet);
InternetCloseHandle(hFile);
//OutputDebugString("\nCHttpDownload:
:
UrlDownloadToFile()--.3");
returnfalse;
}
if(HttpQueryInfo(hFile,HTTP_QUERY_CONTENT_LENGTH,&dwStatusCode1,&dwSize1,NULL))
{
nfilesize=atoi(dwStatusCode1);//filesize.
}
charszBuffer[MAX_BUFFER_SIZE+1]={0};
if(pBuf!
=NULL)//Weonlycopythe1stMAX_BUFFER_SIZEdatatouserbuffer!
!
!
{
unsignedlongnSize=0;
BOOLbRet=InternetReadFile(hFile,szBuffer,MAX_BUFFER_SIZE,&nSize);
szBuffer[nSize]='\0';
//dumpbuffer.
DWORDdwtSize=(*pdwBufSize>nSize)?
nSize:
*pdwBufSize;
memcpy(pBuf,szBuffer,dwtSize);
}
*pdwBufSize=nfilesize;
InternetCloseHandle(hFile);
InternetCloseHandle(hNet);
returntrue;
}
注意,
用HTTP_QUERY_CONTENT_LENGTH只是返回本次请求得到数据的长度,如果要得到整个文件的大小,
用HTTP_QUERY_CONTENT_RANGE,然后解析得到的字符串,就可以了。
HTTP_STATUS_OK=200
***************************************************************************************
用CHttpFile实现简单的GET/POST数据
一、GET数据,下载网页,文件等,用于可下载的文件,不能用于服务端运行的程序,比如.aspx文件等,否则会返回500错误。
CStringstrSentence,strWriteName="1.htm";
CStringstrFileName="http:
//localhost/InDesign/"+strWriteName;
CInternetSessionsess;
CHttpFile*fileGet;
try
{
fileGet=(CHttpFile*)sess.OpenURL(strFileName);
}
catch(CException*e)
{
fileGet=0;
throw;
}
if(fileGet)
{
DWORDdwStatus;
DWORDdwBuffLen=sizeof(dwStatus);
BOOLbSuccess=fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatus,&dwBuffLen);
if(bSuccess&&dwStatus>=200&&dwStatus<300)
{
CStdioFilefileWrite;
if(fileWrite.Open(strWriteName,CFile:
:
modeWrite|CFile:
:
modeCreate))
{
while(fileGet->ReadString(strSentence))
{
fileWrite.WriteString(strSentence+"\n");
}
fileWrite.Close();
AfxMessageBox("下载完毕");
}
else
{
AfxMessageBox("本地文件"+strWriteName+"打开出错.");
}
}
else
{
strSentence.Format("打开网页文件出错,错误码:
%d",dwStatus);
AfxMessageBox(strSentence);
}
fileGet->Close();
deletefileGet;
}
else
AfxMessageBox("不能找到网页文件!
");
sess.Close();
二、POST数据,比如用于提交注册信息等
CStringstrHttpName="http:
//localhost/TestReg/RegForm.aspx";//需要提交数据的页面
CStringstrFormData="username=abc&password=123";//需要提交的数据
CInternetSessionsess;
CHttpFile*fileGet;
CStringstrHeaders=_T("Content-Type:
application/x-www-form-urlencoded");//请求头
try
{
fileGet=(CHttpFile*)sess.OpenURL(strHttpName);//打开文件
}
catch(CException*e)
{
fileGet=0;
throw;
}
CStringstrSentence,strGetSentence="";
if(fileGet)
{
DWORDdwStatus;
DWORDdwBuffLen=sizeof(dwStatus);
BOOLbSuccess=fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatus,&dwBuffLen);
if(bSuccess&&dwStatus>=200&&dwStatus<300)
{
BOOLresult=fileGet->SendRequest(strHeaders,(LPVOID)(LPCTSTR)strFormData,strFormData.GetLength());
while(fileGet->ReadString(strSentence))//读取提交数据后的返回结果
{
strGetSentence=strGetSentence+strSentence+char(13)+char(10);
}
AfxMessageBox(strGetSentence);//显示返回网页内容
}
else
{
strSentence.Format("POST出错,错误码:
%d",dwStatus);
AfxMessageBox(strSentence);
}
fileGet->Close();
deletefileGet;
}
else
AfxMessageBox("不能找到网页文件!
");
sess.Close();
当然也可以用直接用Api函数URLDownloadToFile()来下载一个文件.
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- URLDownloadToFile