如何在没有Indy抛出各种异常的情况下检查特定响应代码(如200 OK)的目标URL。 ConnectionTimeout,ConnectionClosedGracefully等......
例如,如果URL不正确或无法找到或无法访问其主机。即使我试图忽略它们,Indy仍然会出现例外情况。
所以我的问题是如何正确忽略这些例外情况。
答案 0 :(得分:31)
要处理所有异常,并且正如您所说,忽略它们,您可以使用与@ Stijn的答案中的代码几乎相同的代码:
procedure TForm1.Button1Click(Sender: TObject);
var
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create;
try
try
IdHTTP.Get('http://www.example.com');
except
// do just nothing here, if you really want to completely ignore all
// exceptions thrown from inside the try..except block execution and
// if you don't want to indicate somehow, that the exception occured
end;
finally
IdHTTP.Free;
end;
end;
也许有一天你会想要对TIdHTTP
类抛出的某些类型的异常做出某种反应,例如:仅对HTTP协议异常做出反应。这就是我将在这里详细说明的内容。
Indy为不同的场合定义了许多异常类,当某个动作失败时可能会发生这种异常类。以下是您在使用HTTP协议时可能感兴趣的异常类列表:
EIdException
- 它是Indy库使用的基本异常类。当您想要区分Indy引发的异常和您的应用程序抛出的所有其他异常时,它可能对您有用。
EIdSocketError
- 从HTTP协议抽象的角度来看,它是一个低级异常类,它涵盖了某个套接字操作失败时引发的所有异常。这可以帮助您检测网络级别是否存在问题。
EIdConnClosedGracefully
- 此类引发的异常表明服务器端以通用方式关闭与客户端的连接。当您需要对这种情况作出反应时,这可能很有用,例如:通过重新连接到服务器。
EIdHTTPProtocolException
- 在处理特定请求的HTTP响应期间发生错误时,此异常类用于抛出的异常。当从HTTP响应接收到意外的数字HTTP响应代码时,通常会发生这种情况。当您想要专门处理HTTP协议错误时,它会很有用。通过此异常处理,您可以例如对服务器响应返回的某些HTTP状态代码做出反应。
以下是代码框架,显示了上面列出的异常的处理。当然,您不必显示消息,而是执行更有用的操作。并且,您不需要处理所有这些;你可以使用哪些例外以及如何处理:
uses
IdHTTP, IdException, IdStack;
procedure TForm1.Button1Click(Sender: TObject);
var
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create;
try
try
IdHTTP.Get('http://www.example.com');
except
// this exception class covers the HTTP protocol errors; you may read the
// response code using ErrorCode property of the exception object, or the
// same you can read from the ResponseCode property of the TIdHTTP object
on E: EIdHTTPProtocolException do
ShowMessage('Indy raised a protocol error!' + sLineBreak +
'HTTP status code: ' + IntToStr(E.ErrorCode) + sLineBreak +
'Error message' + E.Message);
// this exception class covers the cases when the server side closes the
// connection with a client in a "peaceful" way
on E: EIdConnClosedGracefully do
ShowMessage('Indy reports, that connection was closed gracefully!');
// this exception class covers all the low level socket exceptions
on E: EIdSocketError do
ShowMessage('Indy raised a socket error!' + sLineBreak +
'Error code: ' + IntToStr(E.LastError) + sLineBreak +
'Error message' + E.Message);
// this exception class covers all exceptions thrown by Indy library
on E: EIdException do
ShowMessage('Indy raised an exception!' + sLineBreak +
'Exception class: ' + E.ClassName + sLineBreak +
'Error message: ' + E.Message);
// this exception class is a base Delphi exception class and covers here
// all exceptions different from those listed above
on E: Exception do
ShowMessage('A non-Indy related exception has been raised!');
end;
finally
IdHTTP.Free;
end;
end;
答案 1 :(得分:3)
普通try/except应该可以做到这一点:
try
IdHttp1.Get(...);
Result:=IdHttp1.ResponseCode=200;
except on EIdException do
Result:=false;
end;