PHP code example of amashukov / http-client-php

1. Go to this page and download the library: Download amashukov/http-client-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

amashukov / http-client-php example snippets


use Amashukov\HttpClient\CurlClient;
use Nyholm\Psr7\Factory\Psr17Factory;

$factory = new Psr17Factory();
$client  = new CurlClient($factory, $factory);

$request  = $factory->createRequest('GET', 'https://api.example.test/data');
$response = $client->sendRequest($request);

echo $response->getStatusCode();          // 200
echo (string) $response->getBody();       // raw body

use Amashukov\HttpClient\Pipeline;
use Amashukov\HttpClient\Middleware\HeaderInjectionMiddleware;
use Amashukov\HttpClient\Middleware\RetryMiddleware;

$client = new Pipeline(
    new CurlClient($factory, $factory),
    [
        new HeaderInjectionMiddleware(['X-Api-Key' => $apiKey]),
        new RetryMiddleware(
            maxAttempts: 3,
            retryStatusCodes: [429, 502, 503, 504],
            baseDelayMs: 200,
        ),
    ],
);

$response = $client->sendRequest($request);

use Amashukov\HttpClient\MiddlewareInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

final class LoggingMiddleware implements MiddlewareInterface
{
    public function handle(RequestInterface $request, callable $next): ResponseInterface
    {
        $start    = microtime(true);
        $response = $next($request);
        printf("%s %s -> %d (%.0fms)\n",
            $request->getMethod(),
            $request->getUri(),
            $response->getStatusCode(),
            (microtime(true) - $start) * 1000,
        );

        return $response;
    }
}
bash
composer