amphp / http-client

An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.

Home Page:https://amphp.org/http-client

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Empty post data

haffoudhi opened this issue · comments

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?

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

You probably want to use FormBody instead:

$body = new FormBody;