繁体   English   中英

Guzzle 不发送发布请求

[英]Guzzle does not send a post request

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

谢谢:)

我看到两件事。 参数必须作为字符串( 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不接受这样的请求。

Guzzle 并不是真正的异步。 它更多的是多线程。 这就是为什么你有wait()行来防止当前的 PHP 脚本关闭,直到所有多个旋转线程完成。 如果您删除wait()行,则脚本旋转的 PHP 进程将立即结束所有线程,您的请求将永远不会发送。

因此,您需要 Guzzle(和 Curl)来进行多处理(并发)I/O 而不是异步 I/O。 在您的情况下,您正在处理一个请求,而 Guzzle 承诺简直是矫枉过正。

要使用 Guzzle 发送请求,只需执行以下操作:

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$client = new Client();
$header = ['Content-Type' => 'application/x-www-form-urlencoded'];
$body = json_encode(['id' => '2', 'name' => 'dan']);
$request = new Request('POST', 'http://localhost/async-post/tester.php', $header, $body);

$response = $client->send($request);

此外,您似乎正在使用 form action属性而不是form-params中的实际表单数据。

我发布这个答案是因为我试图通过 php 实现一些真正异步的东西——将 I/O 处理安排为后台任务,继续处理脚本并提供页面; I/O 在后台继续并在不中断客户端的情况下完成。 Laravel 队列是我能找到的最好的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM