delphi – 如何使用IdHTTP检查URL?
如何检查特定响应代码的目标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抛出的特定异常? 也许有一天你会想要对 Indy为不同场合定义了许多异常类,当某个操作失败时可能会发生异常类.以下是异常类的列表,您可能会在使用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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |