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 常用控件属性

Delphi 获取本机公网ip

isnumeric 判断字符串是否为数字

Delphi 高速替换大文本字符串内容

DelphiDelphi提升进程权限为debug权限

Delphi md5加密字符串

Delphi 禁止关机的代码

Delphi中安装和使用kol和mck

Delphi 获取/设置桌面窗口样式的Delphi代码

Delphi webbrowser1 保存文档为 .mht

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



打赏

取消

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

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

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

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

评论

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