drozwmi5440 2019-05-16 23:34
浏览 417
已采纳

如果无法打开流,则重试:HTTP请求失败! 1 PHP

Im trying to open an api and extract some data and about 1/5 times the script runs it errors with a

PHP Warning: file_get_contents(http://192.168.1.52/home.cgi): failed to open stream: HTTP request failed! 1

I would like to retry opening the api on error and then follow through with the rest of the code

This is running on a Pi using PHP5

$inverterDataURL = "http://".$dataManagerIP."/home.cgi";


$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$result = file_get_contents('http://192.168.1.11/home.cgi', false, $context);

20% of the time when running the script it errors trying to open the api and without the api being open i can't grab any data out of it. the rest of the script runs through fine when it opens correctly

  • 写回答

1条回答 默认 最新

  • douhui5953 2019-05-17 00:33
    关注

    You should use a loop for the retry logic that breaks when the result succeeds. A do ... while loop is used here because it guarantees that it'll be run at least once (therefore guaranteeing that $result will be set to something). When the file_get_contents fails, $result will be false:

    <?php
    
    $context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
    
    do {
      $result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
      if (!$result) {
        echo "Waiting 3 seconds.
    ";
        sleep(3);
      }
    } while( !$result);
    

    If the server goes down, you'll probably want something to break the loop after a few tries. This bit will stop trying after 5 failures.

    <?php
    
    $context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
    
    $attempts = 0;
    do {
      $attempts++;
      echo "Attempt $attempts
    ";
      $result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
      if (!$result) {
        echo "Attempt $attempts has failed. Waiting 3 seconds.
    ";
        sleep(3);
      }
    } while( !$result && $attempts < 5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决