- Notifications
You must be signed in to change notification settings - Fork69
An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.
License
amphp/http-client
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
AMPHP is a collection of event-driven libraries for PHP designed with fibers and concurrency in mind.This package provides an asynchronous HTTP client for PHP based onRevolt.Its API simplifies standards-compliant HTTP resource traversal and RESTful web service consumption without obscuring the underlying protocol.The library manually implements HTTP over TCP sockets; as such it has no dependency onext/curl
.
- Supports HTTP/1 and HTTP/2
- Requests concurrently by default
- Pools persistent connections (keep-alive @ HTTP/1.1, multiplexing @ HTTP/2)
- Transparently follows redirects
- Decodes compressed entity bodies (gzip, deflate)
- Exposes headers and message data
- Streams entity bodies for memory management with large transfers
- Supports all standard and custom HTTP method verbs
- Simplifies HTTP form submissions
- Implements secure-by-default TLS (
https://
) - Supports cookies and sessions
- Functions seamlessly behind HTTP proxies
This package can be installed as aComposer dependency.
composer require amphp/http-client
Additionally, you might want to install thenghttp2
library to take advantage of FFI to speed up and reduce the memory usage.
The main interaction point with this library is theHttpClient
class.HttpClient
instances can be built usingHttpClientBuilder
without knowing about the existing implementations.
HttpClientBuilder
allows to register two kinds ofinterceptors, which allows customizing theHttpClient
behavior in a composable fashion.
In its simplest form, the HTTP client takes a request with a URL as string and interprets that as aGET
request to that resource without any custom headers.Standard headers likeAccept
,Connection
orHost
will automatically be added if not present.
useAmp\Http\Client\HttpClientBuilder;$client = HttpClientBuilder::buildDefault();$response =$client->request(newRequest("https://httpbin.org/get"));var_dump($response->getStatus());var_dump($response->getHeaders());var_dump($response->getBody()->buffer());
TheHttpClient
requires aRequest
being passed as first argument torequest()
.TheRequest
class can be used to specify further specifics of the request such as setting headers or changing the request method.
Note
Request
objects are mutable (instead of immutable as inamphp/artax
/ PSR-7).Cloning
Request
objects will result in a deep clone, but doing so is usually only required if requests are retried or cloned for sub-requests.
The constructor requires an absolute request URI.Request::setUri(string $uri)
allows changing the request URI.
$request =newRequest("https://httpbin.org/post","POST");$request->setBody("foobar");$request->setUri("https://google.com/");
Request::getUri()
exposes the request URI of the givenRequest
object.
The constructor accepts an optional request method, it defaults toGET
.Request::setMethod(string $method)
allows changing the request method.
$request =newRequest("https://httpbin.org/post","POST");$request->setBody("foobar");$request->setMethod("PUT");
Request::getMethod()
exposes the request method of the givenRequest
object.
Request::setHeader(string $field, string $value)
allows changing the request headers. It will remove any previous values for that field.Request::addHeader(string $field, string $value)
allows adding an additional header line without removing existing lines.
Request::setHeaders(array $headers)
allows adding multiple headers at once with the array keys being the field names and the values being the header values. The header values can also be arrays of strings to set multiple header lines.
Request::hasHeader(string $field)
checks whether at least one header line with the given name exists.
Request::getHeader(string $field)
returns the first header line with the given name ornull
if no such header exists.
Request::getHeaderArray(string $field)
returns an array of header lines with the given name. An empty array is returned if no header with the given name exists.
Request::getHeaders()
returns an associative array with the keys being the header names and the values being arrays of header lines.
$request =newRequest("https://httpbin.org/post","POST");$request->setHeader("X-Foobar","Hello World");$request->setBody("foobar");
Request::setBody($body)
allows changing the request body. Accepted types arestring
,null
, andHttpContent
.string
andnull
are automatically converted to an instance ofHttpContent
.
Note
HttpContent
is basically a factory for request bodies. We cannot simply accept streams here, because a request body might have to be sent again on a redirect / retry.
$request =newRequest("https://httpbin.org/post","POST");$request->setBody("foobar");
Request::getBody()
exposes the request body of the givenRequest
object and will always return aHttpContent
.
HttpClient::request()
returns aResponse
as soon as the response headers are successfully received.
Note
Response
objects are mutable (instead of immutable as in Artax v3 / PSR-7)
You can retrieve the response's HTTP status usinggetStatus()
. It returns the status as an integer. The optional (and possibly empty) reason associated with the status can be retrieved usinggetReason()
.
$response =$client->request($request);var_dump($response->getStatus(),$response->getReason());
You can retrieve the response's HTTP protocol version usinggetProtocolVersion()
.
$response =$client->request($request);var_dump($response->getProtocolVersion());
Response headers can be accessed by a set of methods.
hasHeader(string)
returns whether a given header is present.getHeader(string)
returns the first header with the given name ornull
if no such header is present.getHeaderArray(string)
returns all headers with the given name, possibly an empty array.getHeaders()
returns all headers as an associative array, see below.
getHeaders()
Format
["header-1" => ["value-1","value-2", ],"header-2" => ["value-1", ],]
getBody()
returns aPayload
, which allows simple buffering and streaming access.
Warning
$chunk = $response->getBody()->read();
reads only a single chunk from the body while$contents = $response->getBody()->buffer()
buffers the complete body.Please refer to thePayload
documentation for more information.
getRequest()
allows access to the request corresponding to the response. This might not be the original request in case of redirects.getOriginalRequest()
returns the original request sent by the client. This might not be the same request that was passed toClient::request()
, because the client might normalize headers or assign cookies.getPreviousResponse
allows access to previous responses in case of redirects, but the response bodies of these responses won't be available, as they're discarded. If you need access to these, you need to disable auto redirects and implement them yourself.
Interceptors allow customizing theHttpClient
behavior in a composable fashion.Use cases range from adding / removing headers from a request / response and recording timing information to more advanced use cases like a fully compliantHTTP cache that intercepts requests and serves them from the cache if possible.
useAmp\Http\Client\Client;useAmp\Http\Client\HttpClientBuilder;useAmp\Http\Client\Interceptor\SetRequestHeader;useAmp\Http\Client\Interceptor\SetResponseHeader;useAmp\Http\Client\Request;$client = (newHttpClientBuilder) ->intercept(newSetRequestHeader('x-foo','bar')) ->intercept(newSetResponseHeader('x-tea','now')) ->build();$response =$client->request(newRequest("https://httpbin.org/get"));$body =$response->getBody()->buffer();
There are two kinds of interceptors with separate interfaces namedApplicationInterceptor
andNetworkInterceptor
.
Most interceptors should be implemented asApplicationInterceptor
.However, there's sometimes the need to have access to the underlying connection properties.In such a case, aNetworkInterceptor
can be implemented to access the used IPs and TLS settings.
Another use-case for implementing aNetworkInterceptor
is an interceptor, that should only ever run if the request is sent over the network instead of served from a cache or similar.However, that should usually be solved with the configuration order of the application interceptors.
The big disadvantage of network interceptors is that they have to be rather quick and can't take too long, because they're only invoked after the connection has been created and the client will run into a timeout if there's no activity within a reasonable time.
AddRequestHeader
AddResponseHeader
ConditionalInterceptor
DecompressResponse
FollowRedirects
ForbidUriUserInfo
IfOrigin
ModifyRequest
ModifyResponse
RemoveRequestHeader
RemoveResponseHeader
RetryRequests
SetRequestHeader
SetRequestHeaderIfUnset
SetResponseHeader
SetResponseHeaderIfUnset
SetRequestTimeout
CookieHandler
PrivateCache
If you useHttpClientBuilder
, the resultingHttpClient
will automatically follow up to ten redirects by default.Automatic following can be customized or disabled (using a limit of0
) usingHttpClientBuilder::followRedirects()
.
TheFollowRedirects
interceptor will only follow redirects with aGET
method.If another request method is used and a307
or308
response is received, the response will be returned as is, so another interceptor or the application can take care of it.Cross-origin redirects will be attempted without any headers set, so any application headers will be discarded.IfHttpClientBuilder
is used to configure the client, theFollowRedirects
interceptor is the outermost interceptor, so any headers set by interceptors will still be present in the response.It is therefore recommended to set headers via interceptors instead of directly in the request.
All previous responses can be accessed from the resultingResponse
viaResponse::getPreviousResponse()
.However, the response body is discarded on redirects, so it can no longer be consumed.If you want to consume redirect response bodies, you need to implement your own interceptor.
TheLogHttpArchive
event listener allows logging all requests / responses including detailed timing information to anHTTP archive (HAR).
These log files can then be imported into the browsers developer tools or online tools likeHTTP Archive Viewer orGoogle's HAR Analyzer.
WarningBe careful if your log files might contain sensitive information in URLs or headers if you submit these files to third parties like the linked services above.
useAmp\Http\Client\HttpClientBuilder;useAmp\Http\Client\EventListener\LogHttpArchive;$httpClient = (newHttpClientBuilder) ->listen(newLogHttpArchive('/tmp/http-client.har')) ->build();$httpClient->request(...);
amphp/http-client
follows thesemver semantic versioning specification like all otheramphp
packages.
Everything in anInternal
namespace or marked as@internal
is not public API and therefore not covered by BC guarantees.
If you discover any security related issues, please emailme@kelunik.com
instead of using the issue tracker.
The MIT License (MIT). Please seeLICENSE
for more information.
About
An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.