代码之家  ›  专栏  ›  技术社区  ›  roev

Guzzle不发送post请求

  •  0
  • roev  · 技术社区  · 7 年前

    我正在使用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 回复  |  直到 7 年前
        1
  •  1
  •   manuerumx    7 年前

    我看到两件事。 参数必须以字符串形式显示( json_encode ) 你也把它们作为标题的一部分,而不是主体。

    然后我添加一个函数来处理响应,如下所示 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();
    

    在这个测试中,谷歌用一个 POST https://google.com 导致 405 Method Not Allowed

    推荐文章