IdHttp Just Get Response Code
TIdHTTP.Head()
is the best option.
However, as an alternative, in the latest version, you can call TIdHTTP.Get()
with a nil
destination TStream
, or a TIdEventStream
with no event handlers assigned, and TIdHTTP
will still read the server's data but not store it anywhere.
Either way, also keep in mind that if the server sends back a failure response code, TIdHTTP
will raise an exception (unless you use the AIgnoreReplies
parameter to specify specific response code values you are interested in ignoring), so you should account for that as well, eg:
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;
UPDATE: to avoid the EIdHTTPProtocolException
being raised on failures, you can enable the hoNoProtocolErrorException
flag in the TIdHTTP.HTTPOptions
property:
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;
Try with http.head()
instead of http.get()
.