相关疑难解决方法(0)

使用TIdHttp逐步下载文件

我想使用TIdHttp(Indy10)实现一个简单的http下载器.我从互联网上找到了两种代码示例.不幸的是,他们都没有100%满足我.这是代码,我想要一些建议.


变式1

var
  Buffer: TFileStream;
  HttpClient: TIdHttp;
begin
  Buffer := TFileStream.Create('somefile.exe', fmCreate or fmShareDenyWrite);
  try
    HttpClient := TIdHttp.Create(nil);
    try
      HttpClient.Get('http://somewhere.com/somefile.exe', Buffer); // wait until it is done
    finally
      HttpClient.Free;
    end;
  finally
    Buffer.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

代码紧凑,易于理解.问题是它在下载开始时分配磁盘空间.另一个问题是我们无法直接在GUI中显示下载进度,除非代码在后台线程中执行(或者我们可以绑定HttpClient.OnWork事件).


变式2:

const
  RECV_BUFFER_SIZE = 32768;
var
  HttpClient: TIdHttp;
  FileSize: Int64;
  Buffer: TMemoryStream;
begin
  HttpClient := TIdHttp.Create(nil);
  try
    HttpClient.Head('http://somewhere.com/somefile.exe');
    FileSize := HttpClient.Response.ContentLength;

    Buffer := TMemoryStream.Create;
    try
      while Buffer.Size < FileSize do
      begin
        HttpClient.Request.ContentRangeStart := Buffer.Size;
        if Buffer.Size + RECV_BUFFER_SIZE < FileSize then
          HttpClient.Request.ContentRangeEnd := Buffer.Size + …
Run Code Online (Sandbox Code Playgroud)

delphi http indy download idhttp

19
推荐指数
1
解决办法
1万
查看次数

标签 统计

delphi ×1

download ×1

http ×1

idhttp ×1

indy ×1