roev
roev

Reputation: 1277

Guzzle does not send a post request

i'm using PHP with Guzzle. I have this code:

$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();

For some reason Guzzle Doesn't send the POST Parameters. Any suggestion?

Thanks :)

Upvotes: 0

Views: 1597

Answers (2)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

Guzzle isn't truely asynchronous. It's more of multi-threading. That is why you have the wait() line to prevent the your current PHP script from closing until all multiple spun threads finish. If you remove the wait() line, the PHP process spun by the script ends immediately with all it's threads and your request is never sent.

Ergo, you need Guzzle (and Curl) for multi-processing(concurrent) I/O and not for asynchronous I/O. In your case, you are processing one request and Guzzle promises are simply an overkill.

To send a request with Guzzle, simply do this:

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);

Also, it seems you are using the form action attribute rather than the actual form data in form-params.

I'm posting this answer because I tried to achieve something really asynchronous with php - Schedule I/O processing as a background task, continue processing script and serve the page; I/O continues in background and completes without disrupting the client. Laravel Queues was the best thing I could find.

Upvotes: 0

manuerumx
manuerumx

Reputation: 1250

I see 2 things. The parameters have to go as string (json_encode) And you were also including them as part of the HEADER, not the BODY.

Then i add a function to handle the response as 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();

In this test Google responds with a Client error: POST https://google.com resulted in a 405 Method Not Allowed

But is ok. Google doesn't accepts request like this.

Upvotes: 1

Related Questions