Delphi - make the Idhttp run in loop if return page not found error

1k views Asked by At

How i can make the Idhttp run in loop if return 404 page not found the problem is 'GOTO CheckAgain' leads into or out of TRY statement

label
  CheckAgain;
begin  
  CheckAgain:
  try
    idhttp.Get(sURL+WebFile[I], S);
  except
    on E: EIdHTTPProtocolException do
    if AnsiPos('404',E.Message) <> 0 then
    begin
      I := I+1;
      goto CheckAgain;
    end;
  end;
end;
2

There are 2 answers

0
Remy Lebeau On BEST ANSWER

You have three options:

  1. use a try/except block in a loop, catching EIdHTTPProtocolException exceptions and checking their ErrorCode property for 404:

    repeat
      try
        IdHttp.Get(sURL+WebFile[I], S);
      except
        on E: EIdHTTPProtocolException do
        begin
          if E.ErrorCode <> 404 then
            raise;
          Inc(I);
          Continue;
        end;
      end;
      Break;
    until False;
    
  2. if you are using an up-to-date version of Indy, you can enable the hoNoProtocolErrorException flag in the TIdHTTP.HTTPOptions property, and then your loop can remove the try/except and check the TIdHTTP.ResponseCode property instead:

    repeat
      IdHttp.Get(sURL+WebFile[I], S);
      if IdHttp.ResponseCode <> 404 then
        Break;
      Inc(I);
    until False;
    
  3. use the overloaded version of the TIdHTTP.Get() method that has an AIgnoreReplies parameter, then you can tell Get() to not raise an EIdHTTPProtocolException exception on a 404 response:

    repeat
      IdHttp.Get(sURL+WebFile[I], S, [404]);
      if IdHttp.ResponseCode <> 404 then
        Break;
      Inc(I);
    until False;
    
0
David Heffernan On

As a general rule, I'd avoid using goto. There are occasions where goto should be used, but they are rare and your problem is not suited.

A while loop would be more commonly used. You'd be able to build in a maximum retry mechanism too. Perhaps like this:

RetryCount := 0;
Succeeded := False;
while RetryCount < MaxRetryCount do
  try
    idhttp.Get(sURL+WebFile[I], S);
    Succeeded := True;
    break; // success, break out of while loop
  except
    on E: EIdHTTPProtocolException do
      if E.ErrorCode = 404 then
        inc(RetryCount)
      else
        raise;

  end;