Bashk
Bashk

Reputation: 95

Delphi XE4 - Exception with IdHTTP in function

Something is not working right here and I wonder if somebody could see the error in the code below.

function CheckUrl(url: String): Boolean;
var
  sResp: String;
begin
  Result := False;      
  try
    sResp := IdHTTP1.Get(url);
  except
    on E: EIdHTTPProtocolException do Result := False;
    on E: EIdConnClosedGracefully do Result := False;
    on E: EIdSocketError do Result := False;
    on E: EIdException do Result := False;
    on E: Exception do Result := False;
  end;
  if IdHTTP1.ResponseCode = 200 then Result := True;
end;

I use this function in OnShow event of the main form:

procedure TForm1.FormShow(Sender: TObject);
var
  urlOk: boolean;
begin
  //code1
  if not CheckURL(Url) then 
    begin
      //code2
    end;
  //some code here
end;

The problem occurs when internet connection is not available. Even if I used try-except method in CheckUrl function, and handled all exceptions, the CheckUrl function does not return False if exception happens and code2 is not executed. Maybe someone will see the mistake and point me in the right direction. Thanks.

Upvotes: 0

Views: 291

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598299

You can greatly simplify your function to the following:

function CheckUrl(url: String): Boolean;
begin
  try
    // using AResponseContent=nil to discard any data received so as not to waste any memory storing it temporarily...
    IdHTTP1.Get(url, TStream(nil));
    Result := True;
  except
    Result := False;
  end;
end;

Alternatively:

function CheckUrl(url: String): Boolean;
begin
  try
    IdHTTP1.Head(url);
    Result := True;
  except
    Result := False;
  end;
end;

If that still does not return the expected result then something is seriously wrong with your project or IDE installation.

Upvotes: 4

Related Questions