Delphi和indy TIDHTTP:区分"未找到服务器"和"未找到"响应错误

use*_*784 2 delphi indy

我正在使用indy TIDHTTP编写一种方法来了解我的互联网服务器是否已关闭或同一服务器上的页面地址不可用.

我复制了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;
Run Code Online (Sandbox Code Playgroud)

但这样我只能检测到服务器响应代码,而不是服务器根本没有响应.我想这是微不足道的,但我不知道这样做的方法是什么?

Rem*_*eau 5

一个EIdHTTPProtocolException当引发异常TIdHTTP成功发送到服务器的请求,并把它发送一个HTTP错误回复返回TIdHTTP.如果服务器不能全部达到,一个不同的异常(通常EIdSocketError,EIdConnectExceptionEIdConnectTimeout)将被改为引发.

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;
Run Code Online (Sandbox Code Playgroud)

  • `EIdConnectTimeout`位于`IdExceptionCore`单元中.`EIdSocketError`位于`IdStack`单元中. (2认同)