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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据