San*_*ira 10 delphi indy indy10 delphi-xe2
我怎样才能检查特定响应代码的目标URL,如200 OK,而Indy不会抛出各种异常.ConnectionTimeout,ConnectionClosedGracefully等......
例如,如果URL不正确或无法找到或无法访问其主机.即使我试图忽略它们,Indy仍然会出现异常.
所以我的问题是如何正确地忽略这些异常.
TLa*_*ama 32
要处理所有异常,并且正如您所说,忽略它们,您可以使用与@ 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;
Run Code Online (Sandbox Code Playgroud)
也许有一天你会想要以某种方式对类引发的某些类型的异常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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15395 次 |
| 最近记录: |