davidecesarano/embryo-client

简单的PSR-18 HTTP客户端实现。

1.0.1 2021-01-08 15:41 UTC

This package is auto-updated.

Last update: 2024-09-08 22:56:28 UTC


README

简单的PSR-18 HTTP客户端。

需求

  • PHP >= 7.1

安装

使用Composer

$ composer require davidecesarano/embryo-client

用法

您可以使用Http客户端工厂提供的getpostputpatchdelete方法。这些方法返回一个Psr\Http\Message\ResponseInterface实例。

use Embryo\Http\Client\ClientFactory;

$http = new ClientFactory;
$response = $http->get('https://example.com/');

当进行POSTPUTPATCH请求时,您可以使用包含数据的数组作为第二个参数向请求发送附加数据。

$response = $http->post('https://example.com/users', [
    'name' => 'Davide',
    'surname' => 'Cesarano'
]);

头部

您可以使用withHeaders方法向请求添加头部。此方法接受键/值对的数组

$response = $http
    ->withHeaders([
        'X-First' => 'foo',
        'X-Second' => 'bar'
    ])
    ->post('https://example.com/users', [
        'name' => 'Davide',
        'surname' => 'Cesarano'
    ]);

Bearer令牌

如果您想快速将Bearer令牌添加到请求的Authorization头部,您可以使用withToken方法

$response = $http
    ->withToken('token')
    ->post('https://example.com/users', [
        'name' => 'Davide',
        'surname' => 'Cesarano'
    ]);

发送原始请求体

如果您在请求时想提供原始请求体,可以使用withJson方法

$response = $http
    ->withJson()
    ->post('https://example.com/users', [
        'name' => 'Davide',
        'surname' => 'Cesarano'
    ]);

附加文件

如果您想发送文件,可以使用withFile方法。此方法接受字段名称和文件绝对路径

$response = $http
    ->withFile('file1', '/path/to/file1')
    ->withFile('file2', '/path/to/file2')
    ->post('https://example.com/upload');

超时

使用timeout方法,您可以指定等待响应的最大秒数

$response = $http
    ->withTimeout(30)
    ->get('https://example.com/users');