Guzzle不发送发布请求

时间:2019-02-05 12:54:40

标签: php guzzle

我正在将PHP与Guzzle结合使用。 我有以下代码:

$client = new Client();
$request = new \GuzzleHttp\Psr7\Request('POST', 'http://localhost/async-post/tester.php',[
    'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
    'form_params' => [
        'action' => 'TestFunction'
    ],
]);


$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

由于某些原因,Guzzle不发送POST参数。 有什么建议吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

我看到两件事。 参数必须作为字符串(json_encode) 而且您还将它们作为HEADER(而不是BODY)的一部分包含在内。

然后我添加了一个函数来处理响应ResponseInterface

$client = new Client();
$request = new Request('POST', 'https://google.com', ['Content-Type' => 'application/x-www-form-urlencoded'], json_encode(['form_params' => ['s' => 'abc',] ]));
/** @var Promise\PromiseInterface $response */
$response = $client->sendAsync($request);
$response->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
    );
$response->wait();

在此测试中,Google会以 客户端错误:POST https://google.com导致了405 Method Not Allowed

但是还可以。 Google不接受这样的请求。

相关问题