使用Delphi编写下载文件程序时,一开始还觉得很顺利,使用URLDownload很方便
function DownloadFile1(SourceFile, DestFile: string): Boolean;begin try CoInitialize(nil); //这个是发现问题后加上去的 Result := UrlDownloadToFile(nil, PChar(SourceFile), PChar(DestFile), 0, nil) = 0; CoUninitialize(); except Result := False; end;end;
但是最后却发现问题了——网页更新了,但是下载回来的页面怎么试都没有更新,查看IIS日志, 发现客户端根本向服务器发出请求,甚至把IE缓存删除了都不更新,晕倒!
最后使用idhttp解决这个问题(uses idHttp)
function DownloadFile(SourceFile, DestFile: string): Boolean;var DownLoadFile:TFileStream; idHttp1:TidHttp; tmp:boolean;begin idhttp1:=TidHttp.Create(nil); tmp:=false; DownLoadFile:=TFileStream.Create(DestFile,fmCreate); try IdHTTP1.Get(SourceFile,DownLoadFile); tmp:=DownLoadFile.Size>0; except tmp:=false; end;
IdHttp1.Free; DownLoadFile.Free; if not tmp then deletefile(DestFile); //下载的文件不存在时删除该空白文件 result:=tmp;
end;
idhttp的异常只能捕获,不能使用finally消除
