Method
HttpClient::sendRequest
Send a PSR-7 request with the client's default options.
Description#
public HttpClient::sendRequest(
RequestInterface $request
): ResponseInterfaceThe request's Cookie and User-Agent headers replace the cookie and userAgent options,
and the other headers are sent as they are. A body that implements MultipartStreamInterface
also sets the Content-Type header. The request is not changed.
Waits for the response headers, suspending only the calling coroutine, and returns a complete
response: status, reason phrase, protocol version and headers. The body keeps streaming, and
a failure while reading it is thrown from the stream read as a NetworkException.
A 4xx or 5xx response is returned like any other. The exception code is cURL's error number
and getRequest() returns the request.
Parameters#
- $request RequestInterface
Return values#
ResponseInterface
Errors / Exceptions#
| Exception | When |
|---|---|
RequestException | The request is invalid: a URL without a host, or with an unsupported scheme |
NetworkException | No response headers arrived: connection refused or reset, DNS failure, TLS failure or timeout |
ClientException | Any other failure, such as too many redirects |
Examples#
use phasync\HttpClient\HttpClient;
use phasync\Psr\Request;
$base = require __DIR__ . '/../server.php';
$client = new HttpClient();
$response = $client->sendRequest(Request::create('GET', "$base/hello"));
echo $response->getStatusCode(), ' ', $response->getReasonPhrase(), "\n";
echo $response->getHeaderLine('Content-Type'), "\n";
echo $response->getBody();
// An error status is a response like any other: nothing is thrown
$response = $client->sendRequest(Request::create('GET', "$base/status/503"));
echo $response->getStatusCode(), ' ', $response->getReasonPhrase(), "\n";Output
200 OK text/plain;charset=UTF-8 Hello, world 503 Service Unavailable
use phasync\Psr\Request;
try {
$response = $client->sendRequest(Request::create('GET', 'https://example.com/'));
echo $response->getStatusCode();
} catch (\Psr\Http\Client\NetworkExceptionInterface $e) {
// connection refused, DNS failure, TLS failure, timeout, connection reset
}See also#
HttpClient::requestSend a request with any method, a body and options for this request only.HttpClient::addMiddlewareFunctionWrapHttpClient::sendRequestin a function that can change the request or the response.