使用Delphi XE将通过WinHTTP下载的文件保存到磁盘

3
答案在这个问题中给出,展示了如何通过在Delphi中导入类型库使用WinHTTP。
我已经导入了WinHTTP的类型库,然后尝试编写一个使用该API的文件下载助手函数。下面是我的代码:
我无法弄清楚如何将IWinHttpRequest.ResponseStream(在TLB文件中声明为OleVariant)保存为流并存储到磁盘中。
// IWinHttpRequest is defined by importing type library of WinHTTP.
// Microsoft WinHTTP Services, version 5.1 (Version 5.1) C:\Windows\system32\winhttp.dll
function Download(const url, filename: String): Boolean;
var
   http: IWinHttpRequest;
   wUrl: WideString;
   fs:TFileStream;
   FileStream:IStream;
   sz,rd,wr:Int64;
begin
  try
   wUrl := url;
   http := CoWinHttpRequest.Create;
   http.open('GET', wurl, False);
   http.send(EmptyParam);

   FStatus := http.status; // 200=OK!
   result := FStatus=200;


   if result then
   begin
     fs := TFileStream.Create(filename, fmCreate, fmShareExclusive );
     try
      FileStream := TStreamAdapter.Create(fs, soReference) as IStream;
      sz := http.ResponseStream.Size;
      http.ResponseStream.CopyTo(FileStream,sz,rd,wr);
     finally
         FileStream :=  nil;
         fs.Free;
     end;
   end;
  except
      result := false;
      // do not raise exceptions.
  end;
end;

WinHTTP_TLB.pas的摘录:

 IWinHttpRequest = interface(IDispatch)
    ['{016FE2EC-B2C8-45F8-B23B-39E53A75396B}']
    ......
    property ResponseStream: OleVariant read Get_ResponseStream;

更新:现在我遇到一个关于ole变量的运行时异常,在调用http.ResponseStream.CopyTo(...)时。
 EOleError 'Variant does not reference an automation object'.

相关:https://dev59.com/tU3Sa4cB1Zd3GeqPwpkA - Warren P
TOleStream 相关:https://dev59.com/HlLTa4cB1Zd3GeqPcamc - Warren P
1个回答

6

Warren,您必须使用AxCtrls.TOleStream类来与Classes.TFileStream通信响应流。

就像这样:

IWinHttpRequest.ResponseStream -> TOleStream -> TFileStream

请查看此示例代码

{$APPTYPE CONSOLE}

uses
  Variants,
  ActiveX,
  Classes,
  AxCtrls,
  WinHttp_TLB,
  SysUtils;


function Download(const url, filename: String): Boolean;
var
   http: IWinHttpRequest;
   wUrl: WideString;
   fs:TFileStream;
   HttpStream :IStream;
   sz,rd,wr:Int64;
   FStatus : Integer;
   OleStream: TOleStream;
begin
  try
   wUrl := url;
   http := CoWinHttpRequest.Create;
   http.open('GET', wurl, False);
   http.send(EmptyParam);

   FStatus := http.status; // 200=OK!
   result := FStatus=200;

   if result then
   begin
    HttpStream:=IUnknown(http.ResponseStream) as IStream;
    OleStream:= TOleStream.Create(HttpStream);
    try
      fs:= TFileStream.Create(FileName, fmCreate);
      try
        OleStream.Position:= 0;
        fs.CopyFrom(OleStream, OleStream.Size);
      finally
        fs.Free;
      end;
    finally
      OleStream.Free;
    end;
   end;

  except
      result := false;
      // do not raise exceptions.
  end;
end;


begin
  try
    Download('http://foo.html','C:\Foo\anyfile.foo');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接