首页 > 解决方案 > Guzzle 不发送发布请求

问题描述

我正在使用带有 Guzzle 的 PHP。我有这个代码:

$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 参数。有什么建议吗?

谢谢 :)

标签: phpguzzle

解决方案


我看到两件事。参数必须以字符串 ( 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

但是没关系。谷歌不接受这样的请求。


推荐阅读