phasync
HttpClient / sendRequest

Method

HttpClient::sendRequest

Send a PSR-7 request with the client's default options.

Description#

public HttpClient::sendRequest(
    RequestInterface $request
): ResponseInterface

The 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#

ExceptionWhen
RequestExceptionThe request is invalid: a URL without a host, or with an unsupported scheme
NetworkExceptionNo response headers arrived: connection refused or reset, DNS failure, TLS failure or timeout
ClientExceptionAny other failure, such as too many redirects

Examples#

Example 1A PSR-18 request, and an error status
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
Example 2
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#