PHP code example of gemvc / http-client

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

    

gemvc / http-client example snippets


use Gemvc\Http\Client\HttpClient;

$client = new HttpClient();
$client->setTimeouts(10, 30)
       ->setRetries(3, 200, [500, 502, 503]);

$response = $client->get('https://api.example.com/users', ['page' => 1]);
$data = $client->post('https://api.example.com/users', ['name' => 'John']);

// Error handling (exceptions enabled by default)
try {
    $response = $client->get('https://api.example.com/data');
} catch (\Gemvc\Http\Client\Exception\NetworkException $e) {
    echo "Network error: {$e->getMessage()}\n";
    if ($e->isDnsError()) {
        echo "DNS resolution failed\n";
    }
}

// Or use error storage (disable exceptions)
$client->throwExceptions(false);
$response = $client->get('https://api.example.com/data');
if ($client->hasErrors()) {
    $error = $client->getLastError();
    echo "Error: {$error->getMessage()}\n";
}

use Gemvc\Http\Client\AsyncHttpClient;

$async = new AsyncHttpClient();
$async->setMaxConcurrency(5)
      ->setTimeouts(10, 30);

$async->addGet('users', 'https://api.example.com/users', ['page' => 1])
      ->addGet('posts', 'https://api.example.com/posts', ['limit' => 10])
      ->addPost('create', 'https://api.example.com/create', ['name' => 'Test']);

$results = $async->executeAll();

foreach ($results as $requestId => $result) {
    if ($result['success']) {
        echo "Request {$requestId}: {$result['body']}\n";
    }
}

use Gemvc\Http\Client\AsyncHttpClient;

// Perfect for APM logging, analytics, or background tasks
$apm = new AsyncHttpClient();
$apm->setTimeouts(2, 5)
    ->addPost('apm-log', 'https://apm.example.com/log', [
        'endpoint' => '/api/User/list',
        'duration' => 0.123,
        'status' => 200
    ])
    ->fireAndForget(); // Does NOT block!

// HTTP Methods
get(string $url, array $queryParams = []): string|false
post(string $url, array $data = []): string|false
put(string $url, array $data = []): string|false
postForm(string $url, array $fields = []): string|false
postMultipart(string $url, array $fields = [], array $files = []): string|false
postRaw(string $url, string $body, string $contentType): string|false

// Configuration
setTimeouts(int $connectTimeout, int $timeout): self
setSsl(?string $cert, ?string $key, ?string $ca = null, bool $verifyPeer = true, int $verifyHost = 2): self
setRetries(int $maxRetries, int $retryDelayMs = 200, array $retryOnHttpCodes = []): self
retryOnNetworkError(bool $retry): self
setUserAgent(string $userAgent): self
throwExceptions(bool $throw): self

// Error Handling
clearErrors(): self
hasErrors(): bool
getErrors(): array<HttpClientException>
getLastError(): ?HttpClientException

// Request Building
addGet(string $requestId, string $url, array $queryParams = [], array $headers = []): self
addPost(string $requestId, string $url, array $data = [], array $headers = []): self
addPut(string $requestId, string $url, array $data = [], array $headers = []): self
addPostForm(string $requestId, string $url, array $fields = [], array $headers = []): self
addPostMultipart(string $requestId, string $url, array $fields = [], array $files = [], array $headers = []): self
addPostRaw(string $requestId, string $url, string $body, string $contentType, array $headers = []): self

// Execution
executeAll(): array<string, array{success: bool, body: string|false, http_code: int, error: string, duration: float, exception: HttpClientException|null, exception_type: string|null}>
fireAndForget(): bool
waitForAll(): array

// Configuration
setMaxConcurrency(int $max): self
setTimeouts(int $connectTimeout, int $timeout): self
setSsl(?string $cert, ?string $key, ?string $ca = null, bool $verifyPeer = true, int $verifyHost = 2): self
setUserAgent(string $userAgent): self
onResponse(string $requestId, callable $callback): self
clearQueue(): self
getQueueSize(): int

// Error Handling
clearErrors(): self
hasErrors(): bool
getErrors(): array<HttpClientException>
getLastError(): ?HttpClientException

// Framework automatically selects implementation based on environment
$api = new \Gemvc\Http\ApiCall(); // Uses package internally
$api->get('https://api.example.com/data');

$client = new HttpClient();
$client->throwExceptions(false); // Store errors instead of throwing

$response = $client->get('https://api.example.com/data');

if ($client->hasErrors()) {
    $error = $client->getLastError();
    // Access error details: $error->getUrl(), $error->getHttpCode(), etc.
}

try {
    $client->get('https://api.example.com/data');
} catch (NetworkException $e) {
    if ($e->isDnsError()) {
        // DNS resolution failed
    } elseif ($e->isSslError()) {
        // SSL/TLS handshake failed
    } elseif ($e->isConnectionError()) {
        // Connection failed
    }
    
    // Get error type description
    echo $e->getErrorTypeDescription();
}