【问题标题】:PHP cURL http 200, wait and run new URLPHP cURL http 200,等待并运行新的 URL
【发布时间】:2018-05-21 10:38:47
【问题描述】:

必须修改现有代码才能使用新的异步 API 调用。原始使用 cURL 发送请求并使用结果。新方法要求我发送初始化请求,等待 10-20 秒或直到 http 200 返回,然后发送查询 cURL 并使用结果,但在检查状态为“已完成”之前不需要。

我对 cURL 很陌生,并且很难理解与它相关的许多帖子,非常欢迎任何帮助。代码是:

function check_boomi($service_id) {
$status="";

初始化新的北向 API 调用

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://testurl.com/init? 
ServiceID=".$service_id."");

在运行“查询”之前等待 http 200 响应

sleep(20);
$result = curl_exec($ch);

运行北向 API 查询

curl_setopt($ch, CURLOPT_URL, "http://testurl.com/query? 
ServiceID=".$service_id."");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Cache-Control: no-cache";
$headers[] = "Postman-Token: d2d57c3e-7c5d-df1b-4b61-dacb6c44b7cg";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} 

检查结果“状态”:

如果“处理中”等待 20 秒,然后重试
如果“已完成”,则使用返回数据

curl_close ($ch);
$data = json_decode($result);
return $data;}

【问题讨论】:

    标签: php http curl wait


    【解决方案1】:

    我省略了一些行,以便您更好地了解逻辑并将代码分为 2 个方法:

    • initApi - 调用初始化 api 请求并等待最多 20 秒的响应
    • runQuery - 调用查询 api 请求 - 在可用时返回数据,否则等待例如20秒再试一次

      //set max execution time to e.g. 2 minutes
      ini_set('max_execution_time', 120);
      
      initApi($service_id);
      $data = runQuery();
      
      function initApi($service_id){
          $ch = curl_init();
          //set init-url and all relevant curl headers
          curl_setopt($ch, CURLOPT_URL, "http://testurl.com/init?ServiceID=".$service_id."");
          //set request timeout to 20 seconds - when taking longer we check with runQuery
          curl_setopt($ch, CURLOPT_TIMEOUT, 20)
      
          $result = curl_exec($ch);
      }
      
      function runQuery(){
          $ch = curl_init();
          //set query url and all relevant headers
      
          $result = curl_exec($ch);
          if (!curl_errno($ch)) {
              //check the response if it's still "processing" or "completed" - i'm not sure how the api returns that
              $status = 
              if($status == "processing") {
                  //wait for 20 seconds and call query again
                  sleep(20);
                  return runQuery();
              }
              else{
                  //return data
              }
          }
      }
      

    您还可以减少睡眠超时 - 然后更频繁地调用查询并检查结果是否可用(我假设查询请求没有阻塞)

    别忘了设置max_execution_time - 默认可能是 30 秒 - 如果你的脚本运行时间更长,请求将会失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多