TIdHTTP.Head()
是最好的选择。
但是,作为替代方案,在最新版本中,您可以TIdHTTP.Get()
使用nil
destinationTStream
或未TIdEventStream
分配事件处理程序的 a 进行调用,并且TIdHTTP
仍会读取服务器的数据,但不会将其存储在任何地方。
无论哪种方式,还请记住,如果服务器发回失败响应代码,TIdHTTP
将引发异常(除非您使用AIgnoreReplies
参数指定您有兴趣忽略的特定响应代码值),因此您也应该考虑到这一点,例如:
procedure Button1Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
try
http.Head(url);
code := http.ResponseCode;
except
on E: EIdHTTPProtocolException do
code := http.ResponseCode; // or: code := E.ErrorCode;
end;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;
procedure Button2Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
try
http.Get(url, nil);
code := http.ResponseCode;
except
on E: EIdHTTPProtocolException do
code := http.ResponseCode; // or: code := E.ErrorCode;
end;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;
更新:为避免EIdHTTPProtocolException
出现故障,您可以hoNoProtocolErrorException
在属性中启用标志TIdHTTP.HTTPOptions
:
procedure Button1Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
http.HTTPOptions := http.HTTPOptions + [hoNoProtocolErrorException];
http.Head(url);
code := http.ResponseCode;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;
procedure Button2Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
http.HTTPOptions := http.HTTPOptions + [hoNoProtocolErrorException];
http.Get(url, nil);
code := http.ResponseCode;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;