drozwmi5440 2019-05-16 15:34
浏览 418
已采纳

如果无法打开流,则重试: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-16 16: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);
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部