sofa/http-client

围绕Guzzle HTTP客户端的工厂包装,简化了懒散的开发工作

v1.1.2 2023-01-31 11:04 UTC

This package is auto-updated.

Last update: 2024-08-29 05:24:56 UTC


README

围绕Guzzle HTTP客户端的包装,简化了启动过程

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Laravel应用程序中最简单的示例 - 即可复制粘贴并运行

use Sofa\HttpClient\Factory;

// register factory in IoC with default app logger
app()->bind(Factory::class, fn () => new Factory(app()->environment('testing'), app('log')->driver()));

// then inject or resolve wherever you need
$httpClient = app(Factory::class)
  ->withOptions(['base_uri' => 'https://api.github.com'])
  ->enableRetries()
  ->enableLogging()
  ->make();
  
$httpClient->get('users/jarektkaczyk');

// et voila! Automatic retries in case of server errors and logging out of the box:
[2020-05-22 12:38:32] local.INFO: GET https://api.github.com/users/jarektkaczyk HTTP/1.1 200 (1351 application/json; charset=utf-8) {"request": , "response": {
  "login": "jarektkaczyk",
  "blog": "https://softonsofa.com",
  "location": "Singapore",
  ...
  }
}

带有更多定制的原始示例

// Raw example
$logger = new Logger('HttpLogger');
$logger->pushHandler(
  new StreamHandler('/path/to/the/log/' . date('Y-m-d') . '.log'))
);

$clientFactory = new Factory($fakeRequests, $logger);
$httpClient = $clientFactory
  ->withOptions([
    'base_uri' => 'https://api.github.com',
    'headers' => [
      'User-Agent' => 'My Awesome Client',
    ],
  ])
  ->enableRetries($retries = 3, $delayInSec = 1, $minStatus = 500)
  ->enableLogging($customLogFormat)
  ->withMiddleware($customGuzzleMiddleware)
  ->make();

测试

Guzzle本身提供了测试工具,但在这里我们让它更加简单。这样你就不必担心设置自定义测试客户端或在代码中到处放置if语句了

$factory = new Factory(true, $logger);
$httpClient = $factory->enableLogging()->make();
$httpClient->get('https://api.github.com/users/jarektkaczyk');
$httpClient->get('https://api.github.com/users/octokit');

$factory->getHistory($httpClient);
=>
[
 [
   "request" => GuzzleHttp\Psr7\Request {#7218},
   "response" => GuzzleHttp\Psr7\Response {#7225},
   "error" => null,
   "options" => [
     "synchronous" => true,
     "handler" => GuzzleHttp\HandlerStack {#7205},
     "allow_redirects" => [
       "max" => 5,
       "protocols" => [
         "http",
         "https",
       ],
       "strict" => false,
       "referer" => false,
       "track_redirects" => false,
     ],
     "http_errors" => true,
     "decode_content" => true,
     "verify" => true,
     "cookies" => false,
     "idn_conversion" => true,
   ],
 ],
 ...