HTTP Client

True\HttpClient sends outbound HTTP requests to external APIs. It supports JSON, XML, and form bodies, query parameters, custom headers, TLS overrides, and proxy routing — with the response handed to a callback you supply.

The request() call

$client->request($method, $endpoint, $callable, $body, $options);
  • $methodGET, POST, PUT, DELETE, …
  • $endpoint — full URL of the API.
  • $callable — closure that receives the response object.
  • $body — array (for JSON / form) or string (raw). Pass null for bodyless GETs.
  • $options — see the table below.

Options

KeyPurpose
headersArray or string of custom headers.
timeoutConnection timeout in seconds. Default 60.
typeBody encoding — json, xml, or form.
tlsv1.2Force TLSv1.2 for older endpoints.
proxyProxy server address.
queryArray appended to the endpoint as a query string.

The response object

The callback receives an object with version, status, headers, and body properties. Headers are an associative array; values can be strings or arrays when the server sent multiple of the same header (e.g. Set-Cookie):

$response = (object) [
    'version' => 'HTTP/1.1',
    'status'  => '200',
    'headers' => [
        'Content-Type' => 'application/json',
        'Set-Cookie'   => ['sessionid=abc123', 'csrftoken=xyz456'],
    ],
    'body'    => '{"message":"Success"}',
];

GET request

use True\HttpClient;

$client = new HttpClient;
$client->request('GET', 'https://api.example.com/data', function ($response) {
    echo "Status: {$response->status}\n";
    echo "Body:   {$response->body}\n";
}, null, [
    'timeout' => 30,
]);

POST with a JSON body

$client = new HttpClient;
$client->request('POST', 'https://api.example.com/users', function ($response) {
    if ($response->status === '200') {
        echo "User created!";
    } else {
        echo "Failed.\n";
        print_r($response->headers);
    }
}, ['name' => 'John Doe', 'email' => 'john@example.com'], [
    'type'    => 'json',
    'headers' => ['Authorization: Bearer token123'],
]);

POST a form body

$client->request('POST', 'https://api.example.com/login', function ($response) {
    // ...
}, ['email' => $email, 'password' => $password], [
    'type' => 'form',
]);

Adding query parameters

$client->request('GET', 'https://api.example.com/search', function ($response) {
    // ...
}, null, [
    'query' => ['q' => 'rate limiting', 'limit' => 10],
]);