delphi检查url是否有效的方法
function CheckUrl(url: string; TimeOut: integer = 5000): boolean;
var
hSession, hfile, hRequest: hInternet;
dwindex, dwcodelen: dword;
dwcode: array[1..20] of char;
res: pchar;
re: integer;
Err1: integer;
j: integer;
begin
{uses wininet;}
if pos('http://', lowercase(url)) = 0 then
url := 'http://' + url;
Result := false;
InternetSetOption(hSession, Internet_OPTION_CONNECT_TIMEOUT, @TimeOut, 4);
hSession := InternetOpen('Mozilla/4.0', INTERNET_OPEN_TYPE_PRECONFIG, nil,
nil, 0);
//设置超时
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(2);
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
400..450: Result := false;
else
Result := True;
end;
if assigned(hfile) then
InternetCloseHandle(hfile);
InternetCloseHandle(hSession);
end;
end;