drewlabs/async-http
提供用于执行异步HTTP请求的实用函数
v0.1.2
2023-09-26 16:47 UTC
Requires
- drewlabs/async: ^0.1.2
Requires (Dev)
- phpunit/phpunit: >=6.0
This package is auto-updated.
Last update: 2024-09-26 18:59:36 UTC
README
此库提供了一个用于执行HTTP请求的异步HTTP客户端。它使用PHP streams
API向资源服务器发送请求,必须在支持PHP streams
和 sockets
API的环境中使用。
用法
要使用此库发送HTTP请求,请参考以下示例
use function Drewlabs\Async\Future\await; use function Drewlabs\Async\Http\createRequest; use function Drewlabs\Async\Http\fetch; // Creates the fetch client $promise = fetch(createRequest('http://www.dneonline.com/calculator.asmx?wsdl', 'GET', null, []), ['debug' => true]); // Debugging should not be used in production $response = await($promise); printf("Content-Length: %d\n\r", strlen($response->getBody()));
如果熟悉 async
语法,可以执行以下操作
use function Drewlabs\Async\Http\createRequest; use function Drewlabs\Async\Http\fetch; // Creates the fetch client $promise = fetch(createRequest('http://www.dneonline.com/calculator.asmx?wsdl', 'GET', null, []), ['debug' => true]); // Debugging should not be used in production // Provide then handlers $promise->then(function($response) { printf($response->getBody()); printf($response->getStatusCode()); }); // wait for request to complete response $promise->wait();
API
-
createRequest
createRequest(string $url, string $method = 'GET', ?string $body = '', $headers = [])
此函数用于创建与fetch
接口兼容的请求实例 -
createResponse
createResponse(string $body = '', int $statusCode = 200, array $headers = [], string $reasonPhrase = 'OK')
创建与fetch
接口返回的实例兼容的响应实例 -
fetch
fetch(RequestInterface $request): ResponseInterface
fetch(RequestInterface[] $requests): ResponseInterface[]
fetch(string $url): ResponseInterface
异步发送HTTP请求的HTTP客户端。