PHP cURL http 200,等待 运行 新 URL

PHP cURL http 200, wait and run new URL

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

我是 cURL 的新手,正在努力了解与之相关的许多 post,欢迎任何帮助。代码是:

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

初始化新的北行API调用

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

在 运行 'query'

之前等待 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);
} 

检查结果'status':

如果'Processing'等待20秒再试
如果 'Completed' 使用 return 数据

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

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

  • initApi - 调用初始化 api 请求并等待最多 20 秒的响应
  • runQuery - 调用查询 api 请求 - returns 可用的数据,否则等待,例如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 秒 - 如果您的脚本运行时间更长,请求将会失败。