【问题标题】:Using WinInet to identify total file size before downloading it在下载之前使用 WinInet 识别文件总大小
【发布时间】:2012-02-28 06:30:30
【问题描述】:

我从第三方网站获得以下来源,解释如何使用 WinInet 从 Internet 下载文件。我对 API 不太熟悉,我查看了 WinInet 单元,但没有看到任何我需要的 API 调用。

我正在做的是添加报告下载文件进度的功能。这个过程我已经包含在TThread 中,一切正常。但是,只缺少一件:在下载之前查找源文件的总大小。

请参阅下面我有评论的地方//HOW TO GET TOTAL SIZE? 这是我需要在开始下载之前找出文件的总大小的地方。我该怎么做呢?因为在下载完成之前,这段代码似乎不知道文件的大小 - 这使得这个添加无关紧要。

procedure TInetThread.Execute;
const
  BufferSize = 1024;
var
  hSession, hURL: HInternet;
  Buffer: array[1..BufferSize] of Byte;
  BufferLen: DWORD;
  f: File;
  S: Bool;
  D: Integer;
  T: Integer;
  procedure DoWork(const Amt: Integer);
  begin
    if assigned(FOnWork) then
      FOnWork(Self, FSource, FDest, Amt, T);
  end;
begin
  S:= False;
  try
    try
      if not DirectoryExists(ExtractFilePath(FDest)) then begin
        ForceDirectories(ExtractFilePath(FDest));
      end;
      hSession:= InternetOpen(PChar(FAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
      try
        hURL:= InternetOpenURL(hSession, PChar(FSource), nil, 0, 0, 0);
        try
          AssignFile(f, FDest);
          Rewrite(f, 1);
          T:= 0; //HOW TO GET TOTAL SIZE?
          D:= 0;
          DoWork(D);
          repeat
            InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
            BlockWrite(f, Buffer, BufferLen);
            D:= D + BufferLen;
            DoWork(D);
          until BufferLen = 0;
          CloseFile(f);
          S:= True;
        finally
          InternetCloseHandle(hURL);
        end
      finally
        InternetCloseHandle(hSession);
      end;
    except
      on e: exception do begin
        S:= False;
      end;
    end;
  finally
    if assigned(FOnComplete) then
      FOnComplete(Self, FSource, FDest, S);
  end;
end;

【问题讨论】:

  • 我实现了这样一个功能,发现使用 WinInet 会导致我的应用程序中发生可怕的“超时错误”。通常需要 100 毫秒的 Http-Head 请求需要 15 秒才能返回。在某些版本的 Windows/WinInet 上从 Delphi 调用 WinInet 是一个已知问题。我提到这一点,以防您以后遇到这种奇怪的故障。如果您可以在这里使用 Indy 或其他非 WinInet(例如 WinHttp),请考虑一下! :-)
  • ..It is a known problem in calling WinInet from Delphi on some versions of Windows/WinInet @WarrenP 我在使用 Delphi 的 WinInet 时从未遇到过这个问题。你能指出一些关于这个主题的文档或链接吗?
  • 这里有一个链接:jgobserve.blogspot.com/2009/03/… -- 我的观察是,问题不限于当底层网络出现故障时,你会等待很长时间。有时一切看起来都很好,除了 winInet 有我无法解释的超时。我在 Python 中编写的代码,或者在 Delphi 中使用 INDY 或 ICS 编写的代码没有表现出相同的失败模式。
  • 我在一年半前发布了这个,当我阅读我的代码时,我意识到我没有使用同步线程保护事件。过去一年我所有最新的线程我都仔细设计了关键部分,但是当我不知道如何使任何东西成为线程安全的时候,这又回来了。

标签: delphi download delphi-xe2 wininet progressive-download


【解决方案1】:

您可以使用 HEAD 方法并检查Content-Length 来检索远程文件的文件大小

检查这两个方法

WinInet

如果要执行 HEAD 方法,则必须使用 HttpOpenRequestHttpSendRequestHttpQueryInfo WinInet 函数。

uses
 SysUtils,
 Windows,
 WinInet;

function GetWinInetError(ErrorCode:Cardinal): string;
const
   winetdll = 'wininet.dll';
var
  Len: Integer;
  Buffer: PChar;
begin
  Len := FormatMessage(
  FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM or
  FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_IGNORE_INSERTS or  FORMAT_MESSAGE_ARGUMENT_ARRAY,
  Pointer(GetModuleHandle(winetdll)), ErrorCode, 0, @Buffer, SizeOf(Buffer), nil);
  try
    while (Len > 0) and {$IFDEF UNICODE}(CharInSet(Buffer[Len - 1], [#0..#32, '.'])) {$ELSE}(Buffer[Len - 1] in [#0..#32, '.']) {$ENDIF} do Dec(Len);
    SetString(Result, Buffer, Len);
  finally
    LocalFree(HLOCAL(Buffer));
  end;
end;


procedure ParseURL(const lpszUrl: string; var Host, Resource: string);
var
  lpszScheme      : array[0..INTERNET_MAX_SCHEME_LENGTH - 1] of Char;
  lpszHostName    : array[0..INTERNET_MAX_HOST_NAME_LENGTH - 1] of Char;
  lpszUserName    : array[0..INTERNET_MAX_USER_NAME_LENGTH - 1] of Char;
  lpszPassword    : array[0..INTERNET_MAX_PASSWORD_LENGTH - 1] of Char;
  lpszUrlPath     : array[0..INTERNET_MAX_PATH_LENGTH - 1] of Char;
  lpszExtraInfo   : array[0..1024 - 1] of Char;
  lpUrlComponents : TURLComponents;
begin
  ZeroMemory(@lpszScheme, SizeOf(lpszScheme));
  ZeroMemory(@lpszHostName, SizeOf(lpszHostName));
  ZeroMemory(@lpszUserName, SizeOf(lpszUserName));
  ZeroMemory(@lpszPassword, SizeOf(lpszPassword));
  ZeroMemory(@lpszUrlPath, SizeOf(lpszUrlPath));
  ZeroMemory(@lpszExtraInfo, SizeOf(lpszExtraInfo));
  ZeroMemory(@lpUrlComponents, SizeOf(TURLComponents));

  lpUrlComponents.dwStructSize      := SizeOf(TURLComponents);
  lpUrlComponents.lpszScheme        := lpszScheme;
  lpUrlComponents.dwSchemeLength    := SizeOf(lpszScheme);
  lpUrlComponents.lpszHostName      := lpszHostName;
  lpUrlComponents.dwHostNameLength  := SizeOf(lpszHostName);
  lpUrlComponents.lpszUserName      := lpszUserName;
  lpUrlComponents.dwUserNameLength  := SizeOf(lpszUserName);
  lpUrlComponents.lpszPassword      := lpszPassword;
  lpUrlComponents.dwPasswordLength  := SizeOf(lpszPassword);
  lpUrlComponents.lpszUrlPath       := lpszUrlPath;
  lpUrlComponents.dwUrlPathLength   := SizeOf(lpszUrlPath);
  lpUrlComponents.lpszExtraInfo     := lpszExtraInfo;
  lpUrlComponents.dwExtraInfoLength := SizeOf(lpszExtraInfo);

  InternetCrackUrl(PChar(lpszUrl), Length(lpszUrl), ICU_DECODE or ICU_ESCAPE, lpUrlComponents);

  Host := lpszHostName;
  Resource := lpszUrlPath;
end;

function GetRemoteFileSize(const Url : string): Integer;
const
  sUserAgent = 'Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101';

var
  hInet    : HINTERNET;
  hConnect : HINTERNET;
  hRequest : HINTERNET;
  lpdwBufferLength: DWORD;
  lpdwReserved    : DWORD;
  ServerName: string;
  Resource: string;
  ErrorCode : Cardinal;
begin
  ParseURL(Url,ServerName,Resource);
  Result:=0;

  hInet := InternetOpen(PChar(sUserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if hInet=nil then
  begin
    ErrorCode:=GetLastError;
    raise Exception.Create(Format('InternetOpen Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
  end;

  try
    hConnect := InternetConnect(hInet, PChar(ServerName), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
    if hConnect=nil then
    begin
      ErrorCode:=GetLastError;
      raise Exception.Create(Format('InternetConnect Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
    end;

    try
      hRequest := HttpOpenRequest(hConnect, PChar('HEAD'), PChar(Resource), nil, nil, nil, 0, 0);
        if hRequest<>nil then
        begin
          try
            lpdwBufferLength:=SizeOf(Result);
            lpdwReserved    :=0;
            if not HttpSendRequest(hRequest, nil, 0, nil, 0) then
            begin
              ErrorCode:=GetLastError;
              raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
            end;

             if not HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, @Result, lpdwBufferLength, lpdwReserved) then
             begin
              Result:=0;
              ErrorCode:=GetLastError;
              raise Exception.Create(Format('HttpQueryInfo Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
             end;
          finally
            InternetCloseHandle(hRequest);
          end;
        end
        else
        begin
          ErrorCode:=GetLastError;
          raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
        end;
    finally
      InternetCloseHandle(hConnect);
    end;
  finally
    InternetCloseHandle(hInet);
  end;

end;

印地

还可以使用 indy 检查此代码。

function GetRemoteFilesize(const Url :string) : Integer;
var
  Http: TIdHTTP;
begin
  Http := TIdHTTP.Create(nil);
  try
    Http.Head(Url);
    result:= Http.Response.ContentLength;
  finally
    Http.Free;
  end;
end;

【讨论】:

  • +1 点,我应该改用 Indy :D 只是为了干净的代码
  • 如果您知道无论如何您都将下载该资源,您就不能发送一个 GET 请求并从中读取 Content-Length 标头吗?它会为您节省一个额外的 HTTP 连接。
  • @RobKennedy - 是的,您可以,只要不使用 Transfer-Encoding: chunked 标头以块的形式发送数据,在这种情况下,不使用 Content-Length 标头,并且没有在收到最后一个块之前知道总大小的方法。
【解决方案2】:

回答如何使用 WinInet 获取下载大小的问题。这是我基于 WinInet 的文件下载器之一。

这是我用来获取下载大小的方法:

function TWebDownloader.GetContentLength(URLHandle: HINTERNET): Int64;
// returns the expected download size.  Returns -1 if one not provided
   var
     SBuffer: Array[1..20] of char;
     SBufferSize: Integer;
     srv: integer;
   begin
     srv := 0;
    SBufferSize := 20;
    if HttpQueryInfo(URLHandle, HTTP_QUERY_CONTENT_LENGTH, @SBuffer, SBufferSize, srv) then
       Result := StrToFloat(String(SBuffer))
    else
       Result := -1;
   end;

使用此方法需要打开请求句柄,并且不需要读取任何数据:

 URLHandle := HttpOpenRequest(ConnectHandle, 'GET', Pchar(sitepath), nil,
                  nil, nil, INTERNET_FLAG_NO_CACHE_WRITE, 0);
 ...
 DownloadSize := GetContentLength(URLHandle);

HTH

【讨论】:

  • +1 好东西,1/6 的代码作为另一个答案 :) 顺便说一句,你的那个巨大的下载器项目进展如何?
  • 我真的很好奇它是如何工作的,因为条件是互斥的 a) 方法是 GET b) 不传输请求的资源。我猜它会在接收到标头后关闭连接。
  • @JerryDodge 它已经满足我的需要,我继续做其他事情。不过,它仍然需要大量清理工作。
【解决方案3】:

修复类型后,看起来更好:

function GetContentLength(URLHandle:HINTERNET):Int64;
// returns the expected download size.  Returns -1 if one not provided
var
 SBufferSize, srv:Cardinal;
begin
 srv:=0;
 SBufferSize:=20;
 if Not HttpQueryInfo(URLHandle, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, {@SBuffer} @Result, SBufferSize, srv) then Result:=-1;
end;

叫它:

{get the file handle}
hURL:=InternetOpenURL(hSession, PChar(URL), nil, 0, 0, 0);
if hURL=Nil then
begin
 InternetCloseHandle(hSession);
 ShowMessage('The link is incorrect!');
 exit;
end;
{get the file size}
filesize:=GetContentLength(hURL);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多