Method
HttpClient::request
Send a request with any method, a body and options for this request only.
Description#
public HttpClient::request(
string $method,
UriInterface|string $url,
mixed $requestData = null,
HttpClientOptions|array|null $options = null
): ResponseInterface$options are applied on top of the client's defaults for this request. A null option
means "not set" and keeps the default, and an array such as headers replaces the default
array instead of merging with it. Entries in headers are Name: value strings.
$requestData as a string or a PSR-7 stream is sent as the body. An array or object is
encoded by the Content-Type header: application/x-www-form-urlencoded when there is none,
or application/json when the header says so. For GET the data goes in the query string.
Unlike sendRequest() this returns a CurlResponse unless a middleware answers with
another response, before the transfer has started, so that several requests can run
together. The transfer starts when the response is first read, and a failure of the transfer
is thrown by that read as a NetworkException, RequestException or
ClientException.
Parameters#
- $method string
- The HTTP method
- $url UriInterface|string
- The URL to fetch
- $requestData mixed = null
- The body: a string, a stream, an array or an object
- $options HttpClientOptions|array|null = null
- Options for this request only
Return values#
The response; a CurlResponse unless a middleware returns another 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 the two above |
Examples#
use phasync\HttpClient\HttpClient;
$base = require __DIR__ . '/../server.php';
$client = new HttpClient();
// Array data is encoded as JSON when the Content-Type header says so
$response = $client->request('PATCH', "$base/echo", ['done' => true], [
'headers' => ['Content-Type: application/json', 'Authorization: Bearer secret-token'],
]);
$echo = json_decode((string) $response->getBody(), true);
echo $echo['method'], ' ', $echo['body'], "\n";
echo $echo['headers']['authorization'], "\n";
// For GET, the data goes in the query string
$response = $client->request('GET', "$base/echo", ['q' => 'phasync', 'page' => 2]);
echo json_encode(json_decode((string) $response->getBody(), true)['query']), "\n";PATCH {"done":true}
Bearer secret-token
{"q":"phasync","page":"2"}$response = $client->request('DELETE', 'https://example.com/items/7', null, [
'headers' => ['Authorization: Bearer ' . $token],
]);
echo $response->getStatusCode();
$response = $client->request('PATCH', 'https://example.com/items/7', ['done' => true], [
'headers' => ['Content-Type: application/json'],
]);See also#
HttpClient::getSend a GET request.HttpClient::postSend a POST request with a body.HttpClient::sendRequestSend a PSR-7 request with the client's default options.