guzzle 6.3发布异步请求

时间:2017-12-03 13:14:39

标签: php guzzle

我试图发送帖子异步请求

    $client = new Client([

        'timeout'  => 2.0,

    ]);

    $request = new \GuzzleHttp\Psr7\Request('POST', 'localhost/test.php' , [   'json' => [
        "username"=>"xyz",
        "password"=>"xyz",
        "first_name"=>"test",
        "last_name"=>"test",
        "email"=>"test@test.com",
        "roles"=>"Administrator"
    ], ]);

    $promise = $client->sendAsync($request)->then(function ($response) {

        echo 'I completed! ' . $response->getBody();
    });
    $promise->wait();

test.php代码是 var_dump($_POST);

结果应该是我设置的变量,但我得到空数组。

2 个答案:

答案 0 :(得分:2)

我认为问题在于您使用的是"json" => [],您可能必须使用"form_params" => []来填充$_POST数组。

请参阅此处的一些文档:http://docs.guzzlephp.org/en/stable/request-options.html#form-params

json选项用于显式需要json作为输入的RESTful API,但在php中,通常$_POST填充了已发布的表单,例如名为<input>的s <form>

答案 1 :(得分:0)

使用如下所示的调度程序功能,请阅读register_shutdown_function

此函数将在php脚本结尾处调用,因此是关闭连接并继续繁重工作的好时机。

    public static function schedulePromise($callable, ...$args)
    {
        register_shutdown_function(function ($callable, ...$args) {
            @session_write_close();
            @ignore_user_abort(true);
            call_user_func($callable, ...$args);
        }, $callable, ...$args);
    }

用户永远不会感到幕后的繁重工作。例如在耗时的http

中等待请求
        $promise = $client->sendAsync($request, ['timeout' => 10])
            ->then(function ($response) {
                // success
            }, function ($response) {
                // failure
            });
        self::schedulePromise([$promise, 'wait'],false);
相关问题