PHP code example of kode / http-client

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

    

kode / http-client example snippets


use Kode\HttpClient\Factory;
use GuzzleHttp\Psr7\Request;

// 创建客户端(自动选择最优驱动)
$client = Factory::create();

// 创建请求
$request = new Request('GET', 'https://httpbin.org/get');

// 发送请求
$response = $client->sendRequest($request);

echo $response->getStatusCode(); // 200
echo $response->getBody();       // 响应内容

use Kode\HttpClient\Factory;

// 创建 Fiber 驱动的客户端
$client = Factory::createFiber([
    'timeout' => 10.0,
    'retries' => 3,
]);

// 或指定驱动类型
$client = Factory::create([
    'driver' => Factory::DRIVER_FIBER,
]);

use Kode\HttpClient\Factory;

// 创建带配置的客户端
$client = Factory::create([
    'driver' => 'fiber',   // 驱动类型(auto|curl|swoole|amp|fiber)
    'timeout' => 10.0,     // 默认超时时间(秒)
    'retries' => 3,        // 最大重试次数
    'logger' => function (string $message) {
        echo "[" . date('Y-m-d H:i:s') . "] " . $message . PHP_EOL;
    },
    'auth' => [            // 认证配置
        'type' => 'bearer',
        'credential' => 'your-bearer-token'
    ],
    'rate_limit' => [      // 限流配置
        'capacity' => 10,
        'rate' => 1
    ],
    'cache' => true,       // 启用缓存
    'trace' => true        // 链路追踪:自动注入 traceparent / X-Context-* 头
]);

// 发送请求
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://httpbin.org/get');
$response = $client->sendRequest($request);

use Kode\HttpClient\Factory;
use Kode\HttpClient\HttpClient;
use Kode\HttpClient\Driver\CurlDriver;
use Kode\HttpClient\Driver\FiberDriver;
use Kode\HttpClient\Driver\SwooleDriver;

// 方式一:通过工厂配置
$client = Factory::create(['driver' => Factory::DRIVER_FIBER]);

// 方式二:使用工厂快捷方法
$client = Factory::createFiber();
$client = Factory::createSwoole();
$client = Factory::createAmp();

// 方式三:手动实例化
$client = new HttpClient(new FiberDriver());

use Kode\HttpClient\Middleware\AuthMiddleware;
use Kode\HttpClient\Middleware\MiddlewareStack;
use Kode\HttpClient\Factory;

// 方式一:通过工厂配置
$client = Factory::create([
    'auth' => [
        'type' => 'bearer',
        'credential' => 'your-bearer-token'
    ]
]);

// 方式二:手动添加中间件
$stack = new MiddlewareStack();
$stack->add(AuthMiddleware::bearer('your-bearer-token'));
// 或
$stack->add(AuthMiddleware::apiKey('your-api-key', 'X-API-Key'));

$client = Factory::createWithMiddleware($stack);

use Kode\HttpClient\Middleware\RateLimitMiddleware;

// 容量 10,每秒生成 1 个令牌
$middleware = new RateLimitMiddleware(10, 1);

// 阻塞模式(等待可用令牌)
$middleware = new RateLimitMiddleware(10, 1, true);

use Kode\HttpClient\Middleware\CacheMiddleware;

// 默认缓存 300 秒
$middleware = new CacheMiddleware();

// 自定义缓存时间
$middleware = new CacheMiddleware(600); // 10 分钟

// 获取缓存统计
$stats = $middleware->getCacheStats();
// ['total' => 10, 'valid' => 8, 'expired' => 2]

// 清除缓存
$middleware->clearCache();

use Kode\HttpClient\Middleware\RetryMiddleware;

// 最多重试 3 次,初始退避 100ms,退避乘数 2.0
$middleware = new RetryMiddleware(3, 100, 2.0);

use Kode\HttpClient\Middleware\TimeoutMiddleware;

// 默认超时 30 秒
$middleware = new TimeoutMiddleware(30.0);

use Kode\HttpClient\Middleware\LoggingMiddleware;

$middleware = new LoggingMiddleware(function (string $message) {
    error_log($message);
});

use Kode\HttpClient\Middleware\TracingMiddleware;

// 仅注入出站请求头
$middleware = new TracingMiddleware();

// 同时把下游响应里的 X-Context-* 上下文回写到当前上下文
$middleware = new TracingMiddleware(propagateResponse: true);

use Kode\HttpClient\Factory;

// 注入出站链路头
$client = Factory::create(['trace' => true]);

// 同时回写下游上下文
$client = Factory::create(['trace' => ['propagate_response' => true]]);

use Kode\HttpClient\Context\Context;

// 设置超时时间
Context::setTimeout(5.0);

// 获取超时时间
$timeout = Context::getTimeout();

// 设置重试次数
Context::setRetryCount(3);

// 获取请求耗时
$elapsed = Context::getElapsedTime(); // 毫秒

// 初始化上下文
$requestId = Context::initialize([
    'timeout' => 10.0,
    'retry_count' => 3,
]);

// 清除上下文
Context::clear();

use Kode\Fibers\Fibers;
use Kode\HttpClient\Factory;
use GuzzleHttp\Psr7\Request;

// 在 Fiber 池中并发发送请求
$results = Fibers::batch(
    ['https://httpbin.org/get', 'https://httpbin.org/post'],
    fn(string $url) => Factory::createFiber()
        ->sendRequest(new Request('GET', $url))
        ->getBody()
        ->getContents(),
    2 // 并发数
);

use Kode\HttpClient\Exception\NetworkException;
use Kode\HttpClient\Exception\RequestException;

try {
    $response = $client->sendRequest($request);
} catch (NetworkException $e) {
    // 网络错误
    echo '网络错误: ' . $e->getMessage();
    echo '请求 URI: ' . $e->getRequestUri();
} catch (RequestException $e) {
    // 请求格式错误
    echo '请求错误: ' . $e->getMessage();
} catch (\Exception $e) {
    // 其他错误
    echo '错误: ' . $e->getMessage();
}
bash
php example/middleware.php