对这个问题的回答显示了在 delphi 中通过类型库导入使用 WinHTTP 是多么容易。
我为 WinHTTP 导入了类型库,然后尝试使用该 api 编写文件下载辅助函数。这是我走了多远:
我似乎无法弄清楚如何将 IWinHttpRequest.ResponseStream(在 TLB 文件中声明为 OleVariant)作为 Stream 保存到磁盘。
// 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'.