Delphi and indy TIDHTTP : distinguish between "server not found" and "not found" response error

StackOverflow https://stackoverflow.com/questions/23411550

  •  13-07-2023
  •  | 
  •  

Question

I am using indy TIDHTTP to code a way to know whether my server on the internet is down or the address of the page on the same server is not available.

I copied the suggestion given in another thread on stackoverflow:

try
  IdHTTP1.Get(mypage_address);
except
  on E: EIdHTTPProtocolException do begin
     if e.errorcode=404 then
        showmessage('404 File not found');
    // use E.ErrorCode, E.Message, and E.ErrorMessage as needed...
  end;
end;

but this way I am only able to detect a server response code and not whether the server did not respond at all. I guess it's trivial but I do not know what is the way to do that?

Was it helpful?

Solution

An EIdHTTPProtocolException exception is raised when TIdHTTP successfully sends a request to the server and it sends an HTTP error reply back to TIdHTTP. If the server cannot be reached at all, a different exception (typically EIdSocketError, EIdConnectException, or EIdConnectTimeout) will be raised instead.

try
  IdHTTP1.Head(mypage_address);
except
  on E: EIdHTTPProtocolException do begin
    ShowMessage(Format('HTTP Error: %d %s', [E.ErrorCode, E.Message]));
  end;
  on E: EIdConnectTimeout do begin
    ShowMessage('Timeout trying to connect');
  end;
  on E: EIdSocketError do begin
    ShowMessage(Format('Socket Error: %d %s', [E.LastError, E.Message]));
  end;
  on E: Exception do begin
    ShowMessage(Format('Error: [%s] %s', [E.ClassName, E.Message]));
  end;
end;

OTHER TIPS

I attempted doing the server/site checking scientifically. but eventually simply came down to this:

function TFrameSiteChecker.GetSiteHeader(const AUrl: string): Integer;
begin
  try
    idhttp1.Head(AUrl);
    Result := idhttp1.ResponseCode;
  except
    on E: exception do
      Result := 0;
  end;
end;

Logic being, getting the head reduces traffic, log sizes etc.

There is one one right result from the function - the return of status code 200, anything else is a fail.

Also I failed to force windows / the system / indy to not buffer/cache content, so also eventually, just run the checker every 30 minutes on a schedule. Otherwise (unless something else clears the cache) after the first connect it always succeeds, even if you unplug the machine from the network!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top