日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Delphi使用THTTPClient实现异步下载

發布時間:2023/12/16 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Delphi使用THTTPClient实现异步下载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先在接口部分需要引用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

總結

以上是生活随笔為你收集整理的Delphi使用THTTPClient实现异步下载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。