delphi下载网站文件(支持https协议)

一、URLDownloadToFile()函数介绍

使用微软提供的URLDownloadToFile function函数,函数原型:

HRESULT URLDownloadToFile(
             LPUNKNOWN            pCaller,
             LPCTSTR              szURL,
             LPCTSTR              szFileName,
  _Reserved_ DWORD                dwReserved,
             LPBINDSTATUSCALLBACK lpfnCB
);

该函数支持http,https协议的网站文件下载,使用简单。微软件官方参考文档:

https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775123(v=vs.85)

二、delphi下对URLDownloadToFile()函数的封装

//uses urlmon;
function DownloadToFile(Source, Dest: string): Boolean;
begin
  try
    Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
  except
    Result := False;
  end;
end;

使用该函数需要注意几点:

  • url链接必须带上http://https://头部;
  • 本地路径为文件的绝对路径;
  • 需要引入单元文件:uses urlmon;
  • 该函数运行时会阻塞主线程,因此最好放到子线程内运行;
  • 使用该函数下载文件比IdHTTP控件简单易用,IdHTTP控件对https协议支持不好;

三、使用示例

1.主线程中使用:

DownloadToFile("https://www.w3school.com.cn/html/html_elements.asp","c:\html_elements.asp");

2.子线程中使用:

//uses urlmon;
function DownloadToFile(Source, Dest: string): Boolean;
begin
  try
    Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
  except
    Result := False;
  end;
end;

function ThreadProc(param: LPVOID): DWORD; stdcall;
begin
  DownloadToFile("https://www.w3school.com.cn/html/html_elements.asp","c:\html_elements.asp");
  Result := 0;
end;

procedure downloadFilesThread();
var
  threadId: TThreadID;
begin
  bDownFiles:=true;
  CreateThread(nil, 0, @ThreadProc, nil, 0, threadId);
end;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值