Delphi使用THTTPClient实现异步下载

该博客介绍了如何使用Delphi的THTTPClient组件进行异步HTTP下载操作。通过创建THTTPClient实例,设置下载进度回调函数,以及处理开始、暂停和结束下载的逻辑,实现了下载文件的可视化进度显示和用户交互。代码示例详细展示了从获取请求头到开始下载,以及在下载过程中更新进度条和速度信息的整个过程。
摘要由CSDN通过智能技术生成

首先在接口部分需要引用System.Net.HttpClient类

uses System.Net.HttpClient,System.IOUtils; 
初始化必需的变量参数

FClient: THTTPClient; //异步下载类
FGlobalStart: Cardinal; //全局计时
FAsyncResult: IAsyncResult; //set and get 异步调用的状态
FDownloadStream: TStream; //下载流

异步下载类的初始化:其中下方的ReceiveDataEvent方法表示响应下载的当前进度:滚动台、百分比等可视化内容可通过其展示给用户

FClient := THTTPClient.Create; //初始化
FClient.OnReceiveData := ReceiveDataEvent;//下载数据进度接收事件
FClient.SecureProtocols := [THTTPSecureProtocol.TLS1,
THTTPSecureProtocol.TLS11, THTTPSecureProtocol.TLS12];//协议类型 可自定义
procedure ReceiveDataEvent(const Sender: TObject;
AContentLength, AReadCount: Int64; var Abort: Boolean);
var
LTime: Cardinal;
LSpeed: Integer;
begin
LTime := TThread.GetTickCount - FGlobalStart;//片段事件
if LTime = 0 then
Exit;
LSpeed := (AReadCount * 1000) div LTime;
// TThread.Queue 将线程放入主线程main窗体执行 用于显示进度
TThread.Queue(nil,
procedure
begin
ProgressBarDownload.Value := AReadCount;
LabelGlobalSpeed.Caption := Format(‘Global speed: %d KB/s’,
[LSpeed div 1024]);
end);
end;
在窗体上放置了一个启动的button按钮,在buttononclick事件中调用SampleDownload方法。SampleDownload方法为实际的下载启动操作

procedure SampleDownload;
var
URL: string;
LResponse: IHTTPResponse;
LFileName: string;
LSize: Int64;
begin
LFileName := EditFileName.Text; //下载文件存放地址
try
URL := EditUrl.Text; //下载地址

LResponse := FClient.Head(URL); //获取请求头
LSize := LResponse.ContentLength; //判断请求头的大小 是否请求成功
Memo1.Lines.Add(Format('Head response: %d - %s', [LResponse.StatusCode,
  LResponse.StatusText]));//打印出请求状态 和 状态内容
LResponse := nil; //释放请求头内容
ProgressBarDownload.Maximum := LSize; //进度条的最大值 要注意的是vcl与fmx进度条maxium不同
ProgressBarDownload.Minimum := 0; //进度条起点
ProgressBarDownload.Value := 0; //进度条当前值
LabelGlobalSpeed.Caption := 'Download speed: 0 KB/s';

Memo1.Lines.Add(Format('Downloading: "%s" (%d Bytes) into "%s"',
  [EditFileName.Text, LSize, LFileName]));

// Create the file that is going to be dowloaded
FDownloadStream := TFileStream.Create(LFileName, fmCreate); //下载流初始化以及文件权限设置
FDownloadStream.Position := 0; //下载流从起点开始 初始化

// Start the download process
FGlobalStart := TThread.GetTickCount;
FAsyncResult := FClient.BeginGet(DoEndDownload, URL, FDownloadStream);//返回异步调用状态 以及 随时可控 可断

finally
BStopDownload.Enabled := FAsyncResult <> nil; //判断异步调用状态
BStartDownload.Enabled := FAsyncResult = nil; //释放
end;
end;

//接收下载的状态 包括自然下载成功或用户人为终止
procedure DoEndDownload(const AsyncResult: IAsyncResult);
var
LAsyncResponse: IHTTPResponse;
begin
try
//判断异步调用的状态
LAsyncResponse := THTTPClient.EndAsyncHTTP(AsyncResult);
//将此线程阻塞到主线程中去 在ui界面上告知用户操作状态
TThread.Synchronize(nil,
procedure
begin
if AsyncResult.IsCancelled then
Memo1.Lines.Add(‘Download Canceled’)
else
begin
Memo1.Lines.Add(‘Download Finished!’);
Memo1.Lines.Add(Format(‘Status: %d - %s’, [LAsyncResponse.StatusCode,
LAsyncResponse.StatusText]));
end;

    BStopDownload.Enabled := False;
    BStartDownload.Enabled := True;
  end);

finally
LAsyncResponse := nil;
FreeandNil(FDownloadStream);
end;
end;
放置了一个停止的Button按钮,在buttononclick中调用FAsyncResult.Cancel;方法可终止下载操作。

完整代码如下:

unit DownloadForm;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.URLClient,
System.Net.HttpClient, System.Net.HttpClientComponent, Vcl.ComCtrls,
Vcl.StdCtrls, System.Types, Vcl.ExtCtrls;

type
TFormDownload = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
EditFileName: TEdit;
EditUrl: TEdit;
BStartDownload: TButton;
LabelGlobalSpeed: TLabel;
BStopDownload: TButton;
Panel2: TPanel;
Memo1: TMemo;
ProgressBarDownload: TProgressBar;
procedure BStartDownloadClick(Sender: TObject);
procedure ReceiveDataEvent(const Sender: TObject; AContentLength: Int64;
AReadCount: Int64; var Abort: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BStopDownloadClick(Sender: TObject);
private
{ Private declarations }
FClient: THTTPClient;
FGlobalStart: Cardinal;
FAsyncResult: IAsyncResult;
FDownloadStream: TStream;
procedure SampleDownload;
procedure DoEndDownload(const AsyncResult: IAsyncResult);
public
{ Public declarations }
end;

var
FormDownload: TFormDownload;

implementation

uses System.IOUtils;
{$R *.dfm}

procedure TFormDownload.BStopDownloadClick(Sender: TObject);
begin
(Sender as TButton).Enabled := False;
FAsyncResult.Cancel;
end;

procedure TFormDownload.DoEndDownload(const AsyncResult: IAsyncResult);
var
LAsyncResponse: IHTTPResponse;
begin
try
LAsyncResponse := THTTPClient.EndAsyncHTTP(AsyncResult);
TThread.Synchronize(nil,
procedure
begin
if AsyncResult.IsCancelled then
Memo1.Lines.Add(‘Download Canceled’)
else
begin
Memo1.Lines.Add(‘Download Finished!’);
Memo1.Lines.Add(Format(‘Status: %d - %s’, [LAsyncResponse.StatusCode,
LAsyncResponse.StatusText]));
end;

    BStopDownload.Enabled := False;
    BStartDownload.Enabled := True;
  end);

finally
LAsyncResponse := nil;
FreeandNil(FDownloadStream);
end;
end;

procedure TFormDownload.ReceiveDataEvent(const Sender: TObject;
AContentLength, AReadCount: Int64; var Abort: Boolean);
var
LTime: Cardinal;
LSpeed: Integer;
begin
LTime := TThread.GetTickCount - FGlobalStart;
if LTime = 0 then
Exit;
LSpeed := (AReadCount * 1000) div LTime;
TThread.Queue(nil,
procedure
begin
ProgressBarDownload.Value := AReadCount;
LabelGlobalSpeed.Caption := Format(‘Global speed: %d KB/s’,
[LSpeed div 1024]);
end);
end;

procedure TFormDownload.FormCreate(Sender: TObject);
begin
FClient := THTTPClient.Create;
FClient.OnReceiveData := ReceiveDataEvent;
FClient.SecureProtocols := [THTTPSecureProtocol.TLS1,
THTTPSecureProtocol.TLS11, THTTPSecureProtocol.TLS12];
end;

procedure TFormDownload.FormDestroy(Sender: TObject);
begin
FDownloadStream.Free;
FClient.Free;
end;

procedure TFormDownload.BStartDownloadClick(Sender: TObject);
begin
BStartDownload.Enabled := False;
SampleDownload;
end;

procedure TFormDownload.SampleDownload;
var
URL: string;
LResponse: IHTTPResponse;
LFileName: string;
LSize: Int64;
begin
LFileName := EditFileName.Text;
try
URL := EditUrl.Text;

LResponse := FClient.Head(URL);
LSize := LResponse.ContentLength;
Memo1.Lines.Add(Format('Head response: %d - %s', [LResponse.StatusCode,
  LResponse.StatusText]));
LResponse := nil;
ProgressBarDownload.Maximum := LSize;
ProgressBarDownload.Minimum := 0;
ProgressBarDownload.Value := 0;
LabelGlobalSpeed.Caption := 'Download speed: 0 KB/s';

Memo1.Lines.Add(Format('Downloading: "%s" (%d Bytes) into "%s"',
  [EditFileName.Text, LSize, LFileName]));

// Create the file that is going to be dowloaded
FDownloadStream := TFileStream.Create(LFileName, fmCreate);
FDownloadStream.Position := 0;

// Start the download process
FGlobalStart := TThread.GetTickCount;
FAsyncResult := FClient.BeginGet(DoEndDownload, URL, FDownloadStream);

finally
BStopDownload.Enabled := FAsyncResult <> nil;
BStartDownload.Enabled := FAsyncResult = nil;
end;
end;

end.

使用上述方法,便可使用Delphi完成异步下载Delphi是真的强大超级大爱

原文地址:https://www.cnblogs.com/ne1620/p/16454384.html

### 回答1: Delphi中的THttpClient组件是一个用于HTTP访问的非常方便的组件。它提供了各种方法来发送HTTP请求并获取服务器的响应。使用THttpClient组件下载文件也是非常简单的。 首先,你需要在使用THttpClient之前添加一个uses HttpClient单元,以便使用该组件。 下载文件的步骤如下: 1. 创建一个THttpClient对象。 ``` var HttpClient: THttpClient; begin HttpClient := THttpClient.Create(nil); end; ``` 2. 设置要下载的文件的URL,并指定要保存文件的本地路径。 ``` var FileURL: string; SavePath: string; begin FileURL := 'http://example.com/file.jpg'; // 文件的URL SavePath := 'C:\Downloads\file.jpg'; // 文件的保存路径 end; ``` 3. 发送HTTP GET请求,下载文件并保存到本地路径。 ``` var FileStream: TFileStream; begin FileStream := TFileStream.Create(SavePath, fmCreate); try HttpClient.Get(FileURL, FileStream); finally FileStream.Free; end; end; ``` 在以上代码中,我们创建一个TFileStream对象来将下载的文件保存到本地路径。然后,通过调用THttpClient的Get方法,将文件下载到FileStream中。 需要注意的是,确保文件的保存路径是有效的,并且拥有写入权限。 这就是使用Delphi的THttpClient组件下载文件的简单过程。你可以根据自己的需求定制代码,并添加错误处理来提高程序的稳定性。 ### 回答2: Delphi是一种强大的编程语言,可以用于开发各种类型的应用程序。其中,THttpClient组件是一个非常有用的组件,可以用于实现从互联网上下载文件。 要使用THttpClient组件进行文件下载,首先需要在Delphi项目中添加THttpClient单元。然后,可以创建一个THttpClient实例,并设置相应的属性。例如,可以设置请求的方法(GET或POST),指定要下载的文件的URL,并设置保存文件的路径。 接下来,可以使用Execute方法执行HTTP请求,并按照设定的路径将文件保存到本地硬盘。执行后,可以检查返回的HttpResponseCode属性来确定请求是否成功。如果返回的HttpResponseCode等于200,表示下载成功。 关于下载进度的处理,THttpClient组件也提供了相应的事件。例如,OnReceiveData事件可以用来处理下载过程中返回的数据块。通过设置OnReceiveData事件的处理程序,可以实时显示下载进度或进行其他操作。 最后,不要忘记在完成下载后释放THttpClient实例,以防止资源泄露。 总之,通过使用Delphi的THttpClient组件,我们可以轻松地下载文件。需要注意的是,在实际使用过程中,应该考虑到网络环境、文件大小和下载速度等因素,以确保下载的稳定性和效率。 ### 回答3: Delphi中的THTTPClient组件是一个用于进行HTTP请求的组件,可以用来下载文件。以下是使用THTTPClient组件下载文件的步骤: 1. 创建一个THTTPClient对象: ```Delphi var HttpClient: THTTPClient; begin HttpClient := THTTPClient.Create; ``` 2. 设置下载文件的URL: ```Delphi HttpClient.Get('<文件的URL>'); ``` 3. 获取下载的文件数据: ```Delphi var ResponseStream: TStream; FileData: TBytes; begin ResponseStream := TMemoryStream.Create; try HttpClient.GetStream(ResponseStream); SetLength(FileData, ResponseStream.Size); ResponseStream.Seek(0, TSeekOrigin.soBeginning); ResponseStream.Read(FileData[0], ResponseStream.Size); finally ResponseStream.Free; end; end; ``` 4. 将文件数据保存到本地文件: ```Delphi var FileStream: TFileStream; begin FileStream := TFileStream.Create('<保存文件的路径>', fmCreate); try FileStream.WriteBuffer(FileData[0], Length(FileData)); finally FileStream.Free; end; end; ``` 5. 释放THTTPClient对象: ```Delphi HttpClient.Free; ``` 以上步骤中,我们首先创建了一个THTTPClient对象,然后使用Get方法设置文件的URL,并使用GetStream方法将文件的数据流读取到TStream对象中。接下来,我们将TStream对象中的文件数据读取到TBytes数组中,并保存到本地文件中。最后,我们释放THTTPClient对象,完成文件的下载过程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值