【问题标题】:Delphi - make the Idhttp run in loop if return page not found errorDelphi - 如果找不到返回页面错误,则使 Idhttp 循环运行
【发布时间】:2015-06-12 05:24:07
【问题描述】:

如果返回 404 页面未找到,我如何让 Idhttp 循环运行 问题是 'GOTO CheckAgain' 导致进入或退出 TRY 语句

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;

【问题讨论】:

  • while True do if ItsTimeToStop then Break;,或者只是while WantToTryAgain do Something;不解析异常消息; EIdHTTPProtocolException 异常有 ErrorCode 成员。
  • @TLama 谢谢while WantToTryAgain do Something 工作得很好,关于异常消息EIdHTTPProtocolException 我不明白
  • 我的意思是你的代码上下文中的E 变量也有包含(已经解析的)错误代码的ErrorCode 成员。您可能会发现更多关于它的信息,例如在this thread.

标签: delphi idhttp


【解决方案1】:

您有三个选择:

  1. 在循环中使用try/except 块,捕获EIdHTTPProtocolException 异常并检查它们的ErrorCode 属性是否为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. 如果您使用的是最新版本的 Indy,您可以在 TIdHTTP.HTTPOptions 属性中启用 hoNoProtocolErrorException 标志,然后您的循环可以删除 try/except 并改为检查 TIdHTTP.ResponseCode 属性:

    repeat
      IdHttp.Get(sURL+WebFile[I], S);
      if IdHttp.ResponseCode <> 404 then
        Break;
      Inc(I);
    until False;
    
  3. 使用具有AIgnoreReplies 参数的TIdHTTP.Get() 方法的重载版本,然后您可以告诉Get() 不要在404 响应中引发EIdHTTPProtocolException 异常:

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

【讨论】:

    【解决方案2】:

    一般来说,我会避免使用goto。在某些情况下应该使用goto,但它们很少见,而且您的问题不适合。

    while 循环会更常用。您也可以建立最大重试机制。可能是这样的:

    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;
    

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多