如何在 PHP 中不接受第一个响应时继续请求



>我是使用 Guzzle 包的新手,我想在响应状态正常或不是时通过 web api 发送数据,我执行一些操作,否则状态等于等待我在 5 秒后再次请求或状态等于尚未休眠 30 秒。这是我的代码

$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://192.168.31.51:8080/requesttrafic/";
       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything

那么如何根据响应状态再次发送呢?谢谢

如果您想在状态不是"正常"的情况下再次发送它,那么:

if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}

如果您所说的状态是指HTTP状态,那么您可以像这样验证:

$status = $response->getStatusCode();
if($status!==200){
 //your request again
}

或者也许我理解错了你的问题。在这种情况下,请详细说明。

 $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}else{
  exit;
}
}

最新更新