如何检查特定响应代码的目标URL,如200 OK,而Indy会抛出各种异常. ConnectionTimeout,ConnectionClosedGracefully等…
例如,如果URL不正确或其主机找不到或无法访问.即使我试图忽略它们,Indy仍然会增加例外.
所以我的问题是如何正确地忽略这些例外.
解决方法
1.如何忽略TIdHTTP抛出的所有异常?
为了处理所有异常,正如你所说,忽略它们,你可以使用与@ 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;
2.如何处理TIdHTTP抛出的特定异常?
也许有一天你会想要对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;