0

In my VCL application, I use TIdHTTP.Get() to retrieve data from a RESTful web service. In my application, I use the following code:

var
  HTTP: TIdHTTP;
  ws: WideString;
begin
  ws := HTTP.Get('http://www.restfulwebservice.com/' + ObjectId);
end;

My application always runs on a Windows workstation, and I never want to close it. However, from time to time, it reports a nasty exception Connection Reset By Peer. This usually happens after some inactivity.

In such cases, I must close the application and re-open it again, because I have no idea how to handle this exception. I want to properly handle it (within a try..except block?) to re-open the connection, so there is no need to close and re-run my app.

Are there any practices on how to catch and handle the above mentioned exception? My research showed me some examples of TIdTCPServer, but not TIdHTTP.

Im using Delphi Berlin 10.1 Subscription Update 2 on Windows 7 x64.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Interface Unknown
  • 713
  • 10
  • 26
  • 1
    You are not calling `HTTP:=TIdHTTP.Create` before calling `HTTP.Get()`. Yes, you need a `try..except` around `Get()`, try calling `HTTP.Disconnect` in it. If you are reusing the same `TIdHTTP` object each time, also try setting `HTTP.Request.Connection:='close';` if you are not making frequent requests. Otherwise, call `HTTP.Free` when done, and then call `TIdHTTP.Create` again next time. – Remy Lebeau May 25 '17 at 16:28
  • @RemyLebeau, sure I call `HTTP := TIdHTTP.Create(nil)` earlier in my code. The lines above are just pseudo-code for brevity. However you pointed to a right thing: I call `TIdHTTP.Create(nil)` in `FormCreate` event and free the object in `FormClose`! Now I understand that is completely wrong. Remy, please copy your comment to the answer, so I can accept it. And again: THANK YOU. You've been the most helpful as usual. – Interface Unknown May 25 '17 at 17:00
  • 1
    There is nothing wrong with creating a single `TIdHTTP` object per Form instance. That alone is not what is causing your issue. More likely the real issue is that `TIdHTTP` is using HTTP 1.1 keep-alives by default, and you are just leaving the HTTP connection open for awhile, so the server eventually times out and closes its end of the connection, which `TIdHTTP` does not detect until the next time you use it. So either disable keep-alives, or else handle the error and retry the request. – Remy Lebeau May 25 '17 at 18:13

0 Answers0