1

注意:此代码在 Delphi XE2 中。

我正在尝试在不使用 UrlMon.dll 的情况下下载文件。

我只想使用wininet。到目前为止,这是我想出的:

uses Windows, Wininet;

procedure DownloadFile(URL:String;Path:String);
Var
  InetHandle:Pointer;
  URLHandle:Pointer;
  FileHandle:Cardinal;
  ReadNext:Cardinal;
  DownloadBuffer:Pointer;
  BytesWritten:Cardinal;
begin
  InetHandle := InternetOpen(PWideChar(URL),0,0,0,0);
  URLHandle := InternetOpenUrl(InetHandle,PWideChar(URL),0,0,0,0);
  FileHandle := CreateFile(PWideChar(Path),GENERIC_WRITE,FILE_SHARE_WRITE,0,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,0);
  Repeat
    InternetReadFile(URLHandle,DownloadBuffer,1024,ReadNext);
    WriteFile(FileHandle,DownloadBuffer,ReadNext,BytesWritten,0);
  Until ReadNext = 0;
  CloseHandle(FileHandle);
  InternetCloseHandle(URLHandle);
  InternetCloseHandle(InetHandle);
end;

我认为问题在于我的循环和“ReadNext”。执行此代码时,它会在正确的路径中创建文件,但代码完成并且文件为 0 字节。

4

2 回答 2

3

我改进了一些你的日常工作,它对我有用:

procedure DownloadFile(URL: string; Path: string);
const
  BLOCK_SIZE = 1024;
var
  InetHandle: Pointer;
  URLHandle: Pointer;
  FileHandle: Cardinal;
  BytesRead: Cardinal;
  DownloadBuffer: Pointer;
  Buffer: array [1 .. BLOCK_SIZE] of byte;
  BytesWritten: Cardinal;
begin
  InetHandle := InternetOpen(PWideChar(URL), 0, 0, 0, 0);
  if not Assigned(InetHandle) then RaiseLastOSError;
  try
    URLHandle := InternetOpenUrl(InetHandle, PWideChar(URL), 0, 0, 0, 0);
    if not Assigned(URLHandle) then RaiseLastOSError;
    try
      FileHandle := CreateFile(PWideChar(Path), GENERIC_WRITE, FILE_SHARE_WRITE, 0,
        CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
      if FileHandle = INVALID_HANDLE_VALUE then RaiseLastOSError;
      try
        DownloadBuffer := @Buffer;
        repeat
          if (not InternetReadFile(URLHandle, DownloadBuffer, BLOCK_SIZE, BytesRead) 
             or (not WriteFile(FileHandle, DownloadBuffer^, BytesRead, BytesWritten, 0)) then
            RaiseLastOSError;
        until BytesRead = 0;
      finally
        CloseHandle(FileHandle);
      end;
    finally
      InternetCloseHandle(URLHandle);
    end;
  finally
    InternetCloseHandle(InetHandle);
  end;
end;

例如一个电话:

  DownloadFile
    ('https://dl.dropbox.com/u/21226165/XE3StylesDemo/StylesDemoSrcXE2.7z',
    '.\StylesDemoXE2.7z');

奇迹般有效。

我所做的更改是:

  • 提供缓冲区
  • 检查对 WriteFile 的调用结果,如果它为 false 或写入的字节数与读取的字节数不同,则引发异常。
  • 更改了变量名称。
  • 命名常量
  • [编辑后] Proper Function 结果检查
  • [编辑后] 使用 try/finally 块进行资源泄漏保护

编辑感谢 TLama 提高对最后两点的认识。

于 2012-11-30T04:27:28.760 回答
-2

首先这是错误的。

InetHandle := InternetOpen(PChar(URL), 0, 0, 0, 0);

需要是

InetHandle := InternetOpen(PChar(USERANGENT), 0, 0, 0, 0);

并且在这里缺少一个 )....

(not InternetReadFile(URLHandle, DownloadBuffer, BLOCK_SIZE, BytesRead) ")"
于 2018-01-31T12:03:20.133 回答