gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:48:53 30 4
gpt4 key购买 nike

this question的回答展示了通过 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;

更新:我现在在调用 http.ResponseStream.CopyTo(...)

时收到有关 ole 变体的运行时异常
 EOleError 'Variant does not reference an automation object'.

最佳答案

沃伦,您必须使用 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.

关于delphi - 使用 Delphi XE 将通过 WinHTTP 下载的文件保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6795915/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com