Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Coroutine\Http\Client->setData(string|array $data): void
The data to be sent for with the HTTP request. Can be a string or a key-value array.
None
Set the body of the HTTP request, in other words the data to be sent with the request.
Content-Type
is set to urlencoded
format, then the client will automatically parse the data through http_build_query
addFile
or addData
and setData
is a string and not an array, the string value will be ignored because of differing formats. When using addFile
or addData
the format is form-data
which is not compatible with a string. However, if setData
is using an array, that key-value array will be added to the requestUsing Execute Method
<?php
use OpenSwoole\Coroutine\HTTP\Client;
co::run(function()
{
$client = new Client('127.0.0.1', 80);
$client->set(['timeout' => 1]);
$client->setHeaders([
'Host' => "localhost",
"User-Agent" => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
$client->setMethod('POST');
// Add data to the request
$client->setData(['msg'=> 'Hello','from'=>'Swoole']);
$status = $client->execute('/index.php');
echo $status . "\n";
var_dump($client->body);
$client->close();
});
The execute()
function just takes the path only, not the domain. This allows you set use setMethod()
to select a HTTP request type like GET, POST, PUT etc. and then add data and execute the request when ready.
Using Post Method
<?php
use OpenSwoole\Coroutine\HTTP\Client;
co::run(function()
{
$client = new Client('127.0.0.1', 80);
$client->set(['timeout' => 1]);
$client->setHeaders([
'Host' => "localhost",
"User-Agent" => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
// No need to set the method, post() does it for us, we send the data as well here
$client->post('/index.php', ['msg'=> 'Hello','from'=>'Swoole']);
echo $client->getStatus() . "\n";
var_dump($client->getBody());
echo $client->body;
$client->close();
});
No need to use setMethod()
when using post()
as it is done for you and forced to use POST
. Using the post()
method means you must add the path but not the domain and then data as the second parameter.