Method
HttpClient::post
Send a POST request with a body.
Description#
public HttpClient::post(
UriInterface|string $url,
mixed $requestData,
HttpClientOptions|array|null $options = null
): ResponseInterfaceAn array or object is sent form-encoded; pass ['headers' => ['Content-Type: application/json']]
to send it as JSON. A MultipartStream is sent as multipart/form-data.
Parameters#
- $url UriInterface|string
- The URL to post to
- $requestData mixed
- The body: a string, a stream, an array or an object
- $options HttpClientOptions|array|null = null
- Options for this request only
Return values#
ResponseInterface
Errors / Exceptions#
| Exception | When |
|---|---|
InvalidArgumentException | For an option name that does not exist |
RuntimeException | For a headers entry without a colon, and for array or object data with a Content-Type other than application/x-www-form-urlencoded or application/json |
Examples#
use phasync\HttpClient\HttpClient;
$base = require __DIR__ . '/../server.php';
$client = new HttpClient();
// An array is sent form-encoded unless a Content-Type header says otherwise
$response = $client->post("$base/echo", ['name' => 'Ada', 'tags' => ['math', 'engines']]);
$echo = json_decode((string) $response->getBody(), true);
echo $echo['headers']['content-type'], "\n";
echo json_encode($echo['form']), "\n";Output
application/x-www-form-urlencoded
{"name":"Ada","tags":["math","engines"]}$response = $client->post('https://example.com/login', ['user' => 'frode', 'password' => $secret]);
$response = $client->post('https://example.com/api', ['name' => 'x'], [
'headers' => ['Content-Type: application/json'],
]);See also#
HttpClient::putSend a PUT request with a body.HttpClient::requestSend a request with any method, a body and options for this request only.MultipartStreamAmultipart/form-datarequest body built from a nested array of fields.