电脑主机系统下载文件

发布时间: 2023-04-16 15:47 阅读: 文章来源:转载
1.1 使用 urlmon 下载文件

urlmon.dll内置于Windows中,可用于从网站下载文件。它支持SSL/TLS连接。但仅限Windows;

在 uses 语句中添加 URLMon 单元。

URLDownloadToFile 函数原型:

function URLDownloadToFile(pCaller: pointer; URL: PChar; FileName: PChar; Reserved: DWORD; lpfnCB : pointer): HResult; stdcall; external ‘urlmon.dll‘ name ‘URLDownloadToFileA‘;

使用示例:

procedure TForm1.Button1Click(Sender: TObject);var Source, Dest: string;begin Source:=‘http://lazarus.freepascal.org‘; Dest:=‘C:\Windows\temp\data.txt‘; if URLDownloadToFile(nil, PChar(Source), PChar(Dest), 0, nil)=0 thenshowmessage(‘Download ok!‘) elseshowMessage(‘Error downloading ‘+Source);end;1.2 使用 fphttpclient 下载文件

fphttpclient作为fcl web包的一部分随FPC提供,也可以单独使用。

在 uses 语句中添加 fphttpclient 单元。

我们可以使用 TFPHttpClient 类实例的 Get 方法来下载文件,示例代码:

program dl_fphttp_d;{$mode delphi}{$ifdef windows}{$apptype console}{$endif}usessysutils, classes, fphttpclient, openssl,opensslsockets;constFilename = ‘testdownload.txt‘;varClient: TFPHttpClient;FS: TStream;SL: TStringList;begin{ SSL initialization has to be done by hand here }InitSSLInterface;Client := TFPHttpClient.Create(nil);FS := TFileStream.Create(Filename,fmCreate or fmOpenWrite);trytry{ Allow redirections }Client.AllowRedirect := true;Client.Get(‘https://google.com/‘,FS); excepton E: EHttpClient dowriteln(E.Message)elseraise;end;finallyFS.Free;Client.Free;end;{ Test our file }if FileExists(Filename) thentrySL := TStringList.Create;SL.LoadFromFile(Filename);writeln(SL.Text);finallySL.Free;end;end.1.3 使用 Synapse 下载文件

Synapse 提供串行端口和 TCP/IP 连接。它与其他库不同,您只需要向代码中添加一些 Synapse Pascal 源代码文件;无需安装软件包等。唯一的例外是,如果您想使用SSL/TLS/SSH等加密,则需要外部加密库。

Synapse 通过阻塞(同步)套接字或有限的非阻塞模式处理网络通信。Synapse 未使用异步套接字。Synapse 包含简单的低级非可视对象,便于无问题地进行编程。(无需多线程同步,无需windows消息处理,…)非常适合命令行实用程序、可视化项目、NT服务等。

在 Synapse 官方网站(http://www.ararat.cz/synapse/doku.php),还可以找到 Synapse 项目的一个补充,名为SynaSer。这是用于阻止串行端口上的通信的库。它是Synapse中的非可视化类,程序员界面与Synapsee非常相似。

使用 Synapse 时,Lazarus、Delphi 需要安装,CodeTyphon 默认已经安装 Synapse。

编写下载文件程序时,在 uses 语句中添加 httpsend 单元。示例代码:

...uses httpsend,...function DownloadHTTP(URL, TargetFile: string): Boolean;varHTTPGetResult: Boolean;HTTPSender: THTTPSend;beginResult := False;HTTPSender := THTTPSend.Create;tryHTTPGetResult := HTTPSender.HTTPMethod(‘GET‘, URL);if (HTTPSender.ResultCode >= 100) and (HTTPSender.ResultCode= 100) and (HTTPSender.ResultCode
•••展开全文
相关文章