PHP code example of amphp / http-client

1. Go to this page and download the library: Download amphp/http-client 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/ */

    

amphp / http-client example snippets


use Amp\Http\Client\HttpClientBuilder;

$client = HttpClientBuilder::buildDefault();

$response = $client->request(new Request("https://httpbin.org/get"));

var_dump($response->getStatus());
var_dump($response->getHeaders());
var_dump($response->getBody()->buffer());

$request = new Request("https://httpbin.org/post", "POST");
$request->setBody("foobar");
$request->setUri("https://google.com/");

$request = new Request("https://httpbin.org/post", "POST");
$request->setBody("foobar");
$request->setMethod("PUT");

$request = new Request("https://httpbin.org/post", "POST");
$request->setHeader("X-Foobar", "Hello World");
$request->setBody("foobar");

$request = new Request("https://httpbin.org/post", "POST");
$request->setBody("foobar");

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

var_dump($response->getStatus(), $response->getReason());

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

var_dump($response->getProtocolVersion());

[
    "header-1" => [
        "value-1",
        "value-2",
    ],
    "header-2" => [
        "value-1",
    ],
]

use Amp\Http\Client\Client;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Interceptor\SetRequestHeader;
use Amp\Http\Client\Interceptor\SetResponseHeader;
use Amp\Http\Client\Request;

$client = (new HttpClientBuilder)
    ->intercept(new SetRequestHeader('x-foo', 'bar'))
    ->intercept(new SetResponseHeader('x-tea', 'now'))
    ->build();

$response = $client->request(new Request("https://httpbin.org/get"));
$body = $response->getBody()->buffer();

use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\EventListener\LogHttpArchive;

$httpClient = (new HttpClientBuilder)
    ->listen(new LogHttpArchive('/tmp/http-client.har'))
    ->build();

$httpClient->request(...);