【问题标题】:how to continue requesting when first response is not accepted in php?当php不接受第一个响应时如何继续请求?
【发布时间】:2017-08-24 02:10:21
【问题描述】:

我是使用 Guzzle 包的新手,我想通过 web api 发送数据,当响应状态为 OK 或 NOT 时,我会执行一些操作,否则状态等于等待我在 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

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

【问题讨论】:

  • 我已经编辑了我的答案,也许这就是你要找的。​​span>
  • 那么完美,如果您的问题已经解决,请在stackoverflow上标记已接受的答案以关闭此线程

标签: php laravel-5 guzzle6


【解决方案1】:

如果你想再次发送它,如果状态不是 'ok' 那么:

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
}

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

【讨论】:

  • 这个答案缺少一些参数 $contents 是响应数据。
  • @jdamour,我已经编辑了我的答案,也许这就是你要找的。​​span>
  • 这是我现在使用的带有 sleep() 函数的多个 if 语句的逻辑
  • @jdamour,那么完美,如果您的问题已经解决,请标记已接受的答案以在 stackoverflow 上关闭此线程。
【解决方案2】:
 $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;
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2010-12-01
    • 2020-05-04
    • 1970-01-01
    • 2019-12-26
    • 2019-07-07
    • 2021-10-01
    • 2021-07-25
    相关资源
    最近更新 更多