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;

相关阅读 >>

Delphi tstringlist.find

Delphi的流操作的语法

Delphi 10.4改进 内联变量声明

Delphi pagecontrol不显示tab方式

Delphi 实现文件分割合并

Delphi 双击关闭pagecontrol中的一个分页

Delphi -- gdi+ Delphi如何让 tgpimage 直接从流中加载图片

Delphi adoquery的post和updatebatch

Delphi响应wmi事件(响应网线断开)

Delphi int64:是Delphi中最大的整数,64位有符号整数

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...