gpt4 book ai didi

delphi - 减少 InternetOpenUrl 超时?

转载 作者:行者123 更新时间:2023-12-01 16:34:46 24 4
gpt4 key购买 nike

此函数检查 URL 是否可以访问:

uses wininet, System.Types,

...

function CheckUrl(url: string): boolean;
var
hSession, hfile, hRequest: hInternet;
dwindex, dwcodelen: dword;
dwcode: array [1 .. 20] of char;
res: pchar;
begin
if pos('http://', lowercase(url)) = 0 then
url := 'http://' + url;
Result := false;
hSession := InternetOpen('InetURL:/1.0', INTERNET_OPEN_TYPE_PRECONFIG,
nil, nil, 0);
if assigned(hSession) then
begin
hfile := InternetOpenUrl(hSession, pchar(url), nil, 0,
INTERNET_FLAG_RELOAD, 0);
dwindex := 0;
dwcodelen := 10;
HttpQueryInfo(hfile, HTTP_QUERY_STATUS_CODE, @dwcode, dwcodelen, dwindex);
res := pchar(@dwcode);
Result := (res = '200') or (res = '302');
if assigned(hfile) then
InternetCloseHandle(hfile);
InternetCloseHandle(hSession);
end;
end;

但是,当没有互联网连接时,该函数仅在 21 秒后返回。那么如何将超时限制为 2 秒呢?

这是一个测试程序:

program CheckURLTest;

{.$APPTYPE CONSOLE}
{.$R *.res}

uses
CodeSiteLogging,
wininet,
System.Types,
System.SysUtils;

function CheckUrl(url: string): boolean;
var
hSession, hfile, hRequest: hInternet;
dwindex, dwcodelen: dword;
dwcode: array [1 .. 20] of char;
res: pchar;
begin
if pos('http://', lowercase(url)) = 0 then
url := 'http://' + url;
Result := false;
hSession := InternetOpen('InetURL:/1.0', INTERNET_OPEN_TYPE_PRECONFIG,
nil, nil, 0);
if assigned(hSession) then
begin
hfile := InternetOpenUrl(hSession, pchar(url), nil, 0,
INTERNET_FLAG_RELOAD, 0);
dwindex := 0;
dwcodelen := 10;
HttpQueryInfo(hfile, HTTP_QUERY_STATUS_CODE, @dwcode, dwcodelen, dwindex);
res := pchar(@dwcode);
Result := (res = '200') or (res = '302');
if assigned(hfile) then
InternetCloseHandle(hfile);
InternetCloseHandle(hSession);
end;
end;

var
TestURL: string;

begin
try
TestURL := 'http://www.google.com';

CodeSite.Send('VOR CheckUrl');
if CheckUrl(TestURL) then
CodeSite.Send(TestURL + ' exists!')
else
CodeSite.Send(TestURL + ' does NOT exist!');

except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;

end.

最佳答案

使用InternetSetOption并设置 接收 连接超时(INTERNET_OPTION_CONNECT_TIMEOUT)。 (由于 @JoshKelley 的评论,已更正为使用 CONNECT 而不是 RECEIVE。)

var
dwTimeOut: DWORD;


dwTimeOut := 2000; // Timeout in milliseconds
InternetSetOption(hSession, INTERNET_OPTION_CONNECT_TIMEOUT,
@dwTimeOut, SizeOf(dwTimeOut));

关于delphi - 减少 InternetOpenUrl 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28774137/

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