PHP 重复curl 请求直到收到httpcode 200

我有一个简单的 PHP 卷曲请求,如下所示:


$request = curl_init('https://some/path/');

curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:'.$token));


$response = curl_exec($request);

$errors = curl_error($request);

$httpcode = curl_getinfo($request, CURLINFO_HTTP_CODE);

curl_close($request);

如果我调用的 url 仍在准备数据,则返回 202;如果准备好,则返回 200。


如何构建逻辑来重复请求,直到收到 200 响应。


BIG阳
浏览 228回答 3
3回答

拉莫斯之舞

供将来参考,而不是无限循环垃圾邮件发送我使用过的请求sleep和break,因此它将每 10 秒尝试一次,最多 1 分钟,如下所示:for($i=0; $i<6; $i++){&nbsp; &nbsp; $request = curl_init('https://some/path/');&nbsp; &nbsp; curl_setopt($request, CURLOPT_RETURNTRANSFER, true);&nbsp; &nbsp; curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:'.$token));&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $response = curl_exec($request);&nbsp; &nbsp; $errors = curl_error($request);&nbsp; &nbsp; $httpcode = curl_getinfo($request, CURLINFO_HTTP_CODE);&nbsp; &nbsp; curl_close($request);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if($httpcode == 200){&nbsp; &nbsp; &nbsp; &nbsp; var_dump($response);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; sleep(10);}

慕妹3146593

你可以使用类似的东西$processCompleted = false;$interval = 2; //seconds$request = curl_init('http://www.example.com/');curl_setopt($request, CURLOPT_RETURNTRANSFER, true);curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:'.$token));while(!$processCompleted) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $response = curl_exec($request);&nbsp; &nbsp; // Check HTTP status code&nbsp; &nbsp; if (!curl_errno($response)) {&nbsp; &nbsp; &nbsp; &nbsp; switch ($http_code = curl_getinfo($request , CURLINFO_HTTP_CODE)) {&nbsp; &nbsp; &nbsp; &nbsp; case 200:&nbsp; # OK&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...//do your stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sleep($interval);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}curl_close($ch);

holdtom

do{&nbsp; &nbsp; $response = curl_exec($request);&nbsp; &nbsp; $httpcode = curl_getinfo($request, CURLINFO_HTTP_CODE);}while($httpcode !== 200);请注意,如果没有 sleep(),它会尽可能快地询问 url,“完成了吗?完成了吗?完成了吗?” 一遍又一遍,如果你想在答案不是 200 时睡觉,也许可以尝试for(;;){&nbsp; &nbsp; $response = curl_exec($request);&nbsp; &nbsp; $httpcode = curl_getinfo($request, CURLINFO_HTTP_CODE);&nbsp; &nbsp; if($httpcode===200){break;}&nbsp; &nbsp; sleep(1);}
打开App,查看更多内容
随时随地看视频慕课网APP