gemz/http-client

Gemz Http Client 是一个简单的 Symfony Http-Client 封装,旨在为大多数用例提供易于开发的体验。

v2.3.1 2020-02-14 22:50 UTC

This package is auto-updated.

Last update: 2024-09-15 08:41:07 UTC


README

Latest Version on Packagist GitHub Tests Action Status Quality Score Total Downloads

Gemz Http Client 是一个薄的 Symfony Http-Client 封装,旨在为大多数用例提供易于开发的体验。带有易于使用的异步和并发请求。

如果你需要更多功能,只需使用 GuzzleSymfony 客户端。

安装

你可以通过 composer 安装此包

composer require gemz/http-client

基本用法

use Gemz\HttpCLient\Client;

$client = Client::create();

// get request
$response = $client->get('https://myapi.com/users');

// json post request
$response = $client
    ->payload(['name' => 'John'])
    ->post('https://myapi.com/users');

// query url parameters
$response = $client
    ->queryParam('page', 20)
    ->get('https://myapi.com/users');
// calls https://myapi.com/users?page=20

客户端初始化

你可以使用初始值配置客户端。配置选项适用于客户端对象发出的所有请求,除非你在请求本身中覆盖了这些选项。

use Gemz\HttpCLient\Client;
use Gemz\HttpCLient\Config;

// Basic client with no config options
$client = Client::create();
$client = new Client();

// Client with config options
$config = Config::make()
    ->header('API-KEY', 'yourkey')
    ->baseUri('https://myapi.com');
    
$response = Client::create($config)->get('users');

所有可能的选项在配置和请求中都是相同的。如果你在配置和请求中使用了相同的选项,则请求选项将覆盖配置选项。

当你需要使用与配置不同的选项时,这会很有用。

$client = Client::create(Config::make()->header('X-KEY', 'yourkey'));

$response = $client->header('X-KEY', 'otherkey')->get('users');

默认设置

有一些默认设置

  • Content-Type : 'application/json'
  • 所有请求都是异步的
  • 最大重定向次数 20
  • 超时默认为 ini_get('default_socket_timeout')
  • 最大持续时间 0 表示无限

配置和请求选项

// Authentication
$client->authBasic('username', 'password');
$client->authBearer('token');

// Headers
$client->header('key', 'value');
$client->headers(['key' => 'value']);

// User-Agent
$client->userAgent('userAgent');

// Query Parameters
$client->queryParam('key', 'value');
$client->queryParams(['key1' => 'value1']);
// will result in ...?key=value&key1=value1

// Timeout in seconds
$client->timeout(10);

// Max Redirects
// 0 means unlimited
$client->allowRedirects(3);
$client->doNotAllowRedirects();

// Max Request <-> Response Duration
// in seconds
$client->maxDuration(30);

// Throw errors if response status code is >= 400
$client->throwErrors();

// Content-Types
$client->contentType('contentType');
$client->asJson();
$client->asFormParams();
$client->asPlain();
$client->asMultipart();

// Multipart form data will automatically transformed in the correct format
// throws an exception if content-type and payload does not match
$client->payload(['key' => 'value']);
$client->payload('my message');

// payload for multipart
$client->payload([
    'key' => 'value',
    'file_field' => Client::fileHandler('pathToFile')
]);

// without verifing ssl
// Default is verifing
$client->doNotVerifySsl();
$client->verifySsl();

// Proxy
$client->useProxy('tcp://...');

// Methods
// Endpoint can also be an URI
$client->get('users/1');
$client->get('https://myapi.com/users/1');
$client->post('users');
$client->put('users/1');
$client->patch('users/1');
$client->head('users/1');
$client->delete('users/1');

// Setting Symfony Specific Client Options
$client->option('<key', '<value');

你也可以向请求传递自定义数据,这些数据将在响应中可用。这在多个并行请求中特别有用,可以用来在响应中识别原始请求。

// can be string, array, object ....
$client->customData(['id' => 182736283]);

// in response
$response->customData(); // outputs ['id' => 182736283] 

响应

请求是完全异步的,除非你读取响应的内容、标题或状态码

$response = $client->get('users/1');

// Content Access
$response->asArray(); // if content is json
$response->asObject(); // if content is json
$response->asCollection(); // if content is json - illuminate collection
$response->asString();
$response->asStream(); // php resource
$response->body();

// Status Code
$response->status(); // integer
$response->isOk(); // true / false 200 - 299
$response->isSuccess(); // true / false 200 - 299
$response->isRedirect(); // true / false 300 - 399
$response->isClientError(); // true / false 400 - 499
$response->isServerError(); // true / false 500 - 599

// Headers
$response->header('content-type');
$response->headers();
$response->contentType();
$response->isJson(); // true / false

// Request Url
$response->requestUrl();

// Execution Time request <-> response
$response->executionTime();

// Custom Data
// Data from request custom data 
$response->customData();

// response infos
// returns info coming from the transport layer, such as "response_headers",
// "redirect_count", "start_time", "redirect_url", etc.
$response->info();

// symmfony response object
$response->response();

异步和并发请求

由于所有请求都是异步的,你可以将请求放入数组中,稍后获取响应。在这种情况下,foreach 循环按请求的顺序获取响应。

$client = Client::create();

$responses = [];

$responses[] = $client->get('users/1');
$responses[] = $client->get('users/2'));
$responses[] = $client->get('users/3');

// responses are in order of the requests
foreach ($responses as $response) {
    echo $response->status());
}

如果你有很多请求,这种方法更好、更快。响应的顺序与请求的顺序无关。 这是完全异步的

$client = Client::create();

$responses = [];

for ($i = 1; $i < 300; $i++) {
    $responses[] = $client
        // using custom data to identify the request in the response
        ->customData('id:' . $i)
        ->get("users/{$i}");
}

// Using the Stream Object to access the responses
foreach ($client->stream($responses) as $response => $chunk) {
    Stream::from($response, $chunk)
        ->then(function (Response $response) {
            // success - do something with the response
            echo $response->customData()
        })
        ->timeout(function (Response $response) {
            // timeout - do something with the response        
        })
        ->catch(function ($exception, Response $response) {
            // exception was thrown
        });
}

流响应和块

使用流对象是接收响应最快的方式。你可以监听这些事件

use Gemz\HttpClient\Stream;

foreach ($client->stream($response) as $response => $chunk) {
    $stream = Stream::for($response, $chunk);
    
    // fulfilled
    // callable must use response
    $stream->then(/* callable */);

    // timeout
    // callable must use response
    $stream->timeout(/* callable */);

    // rejected
    // callable must use exception, response
    $stream->catch(/* callable */);
}

测试

composer test
composer phpstan
composer test-coverage

更改日志

请参阅 CHANGELOG 了解最近更改的详细信息。

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全性

如果你发现任何安全相关的问题,请通过电子邮件 stefan@sriehl.com 而不是使用问题跟踪器。

致谢

支持我们

Gemz.io 由 Stefan Riehl 维护。你可以在 Gemz.io github 上找到所有开源项目。

许可

MIT 许可证 (MIT)。请参阅 License File 了解更多信息。