Indy: getting response despite exceptions or 4xx HTTP status codes
Posted by jpluimers on 2016/12/07
Formy snippet archive (thanks Walter Prins for answering and Oliver Funcke for asking and elaborating on the answer):
in the case of error, you can get what would’ve normally been in the contentstream from the
ExceptionObj.ErrorMessage
property. So you can use something like the following if you want to get the content response regardless of http response code (untested):var FResponseStream: TStringStream; FRequestURL, Content : String; begin //.... etc etc try FIdHTTP.Get(FRequestURL, FResponseStream); Content := FResponseStream.DataString; except on E:EIdHTTPProtocolException do Content := E.ErrorMessage; end; // At this point, "Content" contains the response body, both for // successful (200) as well as other response codes. //.... etc etc end;….
You can even do it simpler:
Response := IdHTTP.Get('http://host/path', [404]);
Source: delphi – Indy and REST – Can I prevent exceptions? – Stack Overflow
–jeroen
via:
Remy Lebeau said
Note that the AIgnoreReplies parameter is only available in TIdHTTP.Get() (and TIdHTTP.DoRequest()). You can’t use it for POST requests (unless you call DoRequest() directly). However, there is another option. The TIdHTTP.HTTPOptions property has hoNoProtocolErrorException and hoWantProtocolErrorContent flags available. If hoNoProtocolErrorException is enabled, an HTTP error will not raise EIdHTTPProtocolException, the request will just end normally. In that scenario, if hoWantProtocolErrorContent is enabled then the error content will be saved in the caller’s ContentStream, otherwise it will be discarded.
jpluimers said
Thanks for the insight. Much appreciated!