【发布时间】:2013-01-30 12:25:13
【问题描述】:
Delphi 6 教授,Win7 操作系统。
我有这段代码可以通过 URL 获取文件大小:
function TDDWIToolObject.GetFileSize(out Size: Int64): boolean;
var
hInet: HINTERNET;
hRequest : HINTERNET;
lpdwBufferLength: DWORD;
lpdwReserved : DWORD;
ServerName: string;
Resource: string;
FileSizeBuffer : array[0..32] of char;
//SizeCard : Cardinal;
begin
ParseURL(Url, ServerName, Resource);
Result := False;
Size := 0;
hInet := InternetOpen(PChar(_UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if hInet=nil then begin
FErrorCode := GetLastError;
Exit;
end;
try
hRequest := InternetOpenUrl(hInet, PChar(URL), PCHar(Headers), Length(HEaders), 0, 0);
try
FillChar(FileSizeBuffer, SizeOf(FileSizeBuffer), #0);
lpdwBufferLength := SizeOf(FileSizeBuffer);
lpdwReserved :=0;
if not HttpQueryInfo(
hRequest,
HTTP_QUERY_CONTENT_LENGTH,
@FileSizeBuffer, lpdwBufferLength, lpdwReserved) then begin
FErrorCode:=GetLastError;
Exit;
end;
Size := StrToInt64(StrPas(FileSizeBuffer));
Result := True;
finally
InternetCloseHandle(hRequest);
end;
finally
InternetCloseHandle(hInet);
end;
end;
在我的机器 + DSL 连接上运行良好。
但是当我在其他完全受保护的地方(代理+许多策略)检查此代码时,我得到错误代码 12150... :-(
有趣的是,当我使用这段代码时,我可以下载这个文件:
function TDDWIToolObject.DownloadFile;
var
hInet: HINTERNET;
hFile: HINTERNET;
pbuffer: Pointer;
bytesRead: DWORD;
Stm : TFileStream;
TotalBytes : Int64;
AbortIt : boolean;
begin
Result := False;
FErrorCode := -1;
FAborted := False;
hInet := InternetOpen(PChar(_UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if hInet = nil
then begin
FErrorCode := GetLastError;
Exit;
end;
try
hFile := InternetOpenURL(hInet, PChar(URL), PChar(FHeaders), Length(FHeaders), 0, 0);
if hFile = nil
then begin
FErrorCode := GetLastError;
Exit;
end;
try
Stm := TFileStream.Create(FN, fmCreate);
try
GetMem(pbuffer, FBufferSize);
try
TotalBytes := 0; AbortIt := False;
while (not FAborted) do begin
if not InternetReadFile(hFile, pbuffer, FBufferSize, bytesRead) then begin
FErrorCode := GetLastError;
Exit;
end;
if bytesRead > 0 then begin
Stm.WriteBuffer(pbuffer^, bytesRead);
if Assigned(FOnBytesArrived)
then begin
inc(TotalBytes, bytesRead);
FOnBytesArrived(Self, TotalBytes, AbortIt);
if AbortIt
then Abort;
end;
end else begin
break;
end;
end;
finally
FreeMem(pbuffer);
end;
if not FAborted
then Result := True;
finally
Stm.Free;
end;
finally
InternetCloseHandle(hFile);
end;
finally
InternetCloseHandle(hInet);
end;
end;
这很有趣,因为系统管理员允许在代理中对这个 URL 的请求,并且下载对我有用 - 只有内容长度请求失败。
我想问一个问题,但很难做到,因为其中很多都在我的脑海中...... 您知道我们可以做些什么来允许这些请求吗? 也许 HttpRequest 使用另一个端口,或者一些“非法”的不可代理? 或者我的代码似乎是错误的?为什么它在非保护区工作?下载和获取内容长度请求有什么区别?
所以问题是总结格式:你知道我可以做些什么来在下载之前获取文件大小吗?
谢谢。
【问题讨论】:
-
不,如果我添加 flag_number,我得到的结果是数字(我知道红衣主教)。我更喜欢符合 Int64 的字符串。
标签: delphi download wininet content-length