delphi 检测一个网络连接是否有效带超时


//检测一个网络连接是否有效
function CheckUrl(url: string; TimeOut:integer=20000): boolean;
var
hSession, hfile, hRequest: hInternet;
dwindex, dwcodelen: dword;
dwcode: array[1..20] of char;
res: pchar;
re: integer;
Err1: integer;
j: integer;
begin
if pos('http://', lowercase(url)) = 0 then
url := 'http://' + url;
Result := false;
hSession := InternetOpen('Mozilla/4.0', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
InternetSetOption(hSession, Internet_OPTION_CONNECT_TIMEOUT, @TimeOut, 4);
if assigned(hsession) then
begin
j := 1;
while true do
begin
hfile := InternetOpenUrl(hsession, pchar(url), nil, 0, INTERNET_FLAG_RELOAD, 0);
if hfile = nil then
begin
j := j + 1;
Err1 := GetLastError;
if j > 5 then break;
if (Err1 <> 12002) or (Err1 <> 12152) then break;
sleep(2000);
end
else begin
break;
end;
end;
dwIndex := 0;
dwCodeLen := 10;
HttpQueryInfo(hfile, HTTP_QUERY_STATUS_CODE, @dwcode, dwcodeLen, dwIndex);
res := pchar(@dwcode);
re := strtointdef(res, 404);
case re of
200..299: result := True;
401..403: result := True;
else result := False;
end;
if assigned(hfile) then
InternetCloseHandle(hfile);
InternetCloseHandle(hsession);
end;
end;

联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678