amphp / http-client

An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.
https://amphp.org/http-client
MIT License
706 stars 66 forks source link

Empty post data #304

Closed haffoudhi closed 2 years ago

haffoudhi commented 2 years ago

Hey, I m new to http-client, I m trying POST request with post data. The request is POST but the data is empty.

here's the code:

Loop::run(function () {
    $client = HttpClientBuilder::buildDefault();

    $baseUrl = 'http://localhost/test.php';

    $response = yield $client->request(new Request($baseUrl, 'POST', 'test1=1&test2=2'));

    var_dump($response->getStatus());
    var_dump($response->getHeaders());
    var_dump(yield $response->getBody()->buffer());die;
});

here's test.php code:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
       // $_POST is empty, it should be "test1=1&test2=2"
       echo '<pre>';print_r($_POST);exit('POST');
} else {
       exit('GET');
}

Can you tell me how to build a post request correctly?

haffoudhi commented 2 years ago

I found the solution by using addHeader.

$request = new Request($url, 'POST', '');
$request->setBody('test1=1&test2=2');
$request->addHeader('Content-Type', 'application/x-www-form-urlencoded');
kelunik commented 2 years ago

You probably want to use FormBody instead: https://github.com/amphp/http-client/blob/4daa9998c955aa9f14ae0096946a3d78a2f32490/examples/basic/4-forms.php#L19