對this question的回答顯示,通過delphi中的類型庫導入來使用WinHTTP是多麼容易。將使用WinHTTP下載的文件保存到磁盤,使用Delphi XE
我導入了WinHTTP類型庫,然後嘗試使用該API編寫文件下載幫助函數。以下是我得到了多少:
我似乎無法弄清楚如何將IWinHttpRequest.ResponseStream(在TLB文件中聲明爲OleVariant)作爲Stream保存到磁盤。從WinHTTP_TLB.pas
// 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;
摘錄:
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'.
相關:http://stackoverflow.com/questions/2771551/cast-object-as-olevariant-in-delphi –
TOleStream相關:http://stackoverflow.com/questions/4443376/how-to-free-tolestream-in-this-bit-of-code –