mnapoli/bof

面向人类的HTTP客户端

0.1.1 2021-01-31 17:17 UTC

This package is auto-updated.

Last update: 2024-09-09 22:56:34 UTC


README

面向人类的HTTP客户端。

Build Status Latest Version

为什么?

Bof是一款旨在尽可能用户友好的HTTP客户端。

它使得最经典的使用案例,如下载文件、与JSON API交互或提交表单,尽可能简单。

由于Bof基于Guzzle,可以通过直接使用Guzzle的方法来解决更复杂的使用案例。

总之,Bof

  • 用户友好
  • 避免在配置中使用魔法字符串和数组:相反,它提供显式、类型化和文档化的方法,这些方法可以由IDE自动完成
  • 提供合理的默认值:原生支持JSON,4xx和5xx响应抛出异常,默认超时时间较短
  • 符合PSR-7规范

未来计划

  • PSR-18合规性(HTTP客户端标准)
  • 弹性机制,如重试、退避等。

需要简短的说明吗?以下是Bof与Guzzle的比较

// Bof
$http = new Bof\Http;
$createdProduct = $http
    ->withHeader('Authorization', 'Token abcd')
    ->postJson('https://example.com/api/products', [
        'Hello' => 'world',
    ])
    ->getData();

// Guzzle
$client = new GuzzleHttp\Client([
    'headers' => [
        'Authorization' => 'Token abcd',
    ],
]);
$response = $client->request('POST', 'https://example.com/api/products', [
   'json' => [
        'Hello' => 'world',
   ]
]);
$createdProduct = json_decode($response->getBody()->__toString(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception('There was an error while decoding the JSON response');
}

我们需要新的HTTP客户端吗?

可能不需要。如果这个客户端吸引人们的兴趣,这可能意味着我们的现有流行的HTTP客户端可能需要一个更简单的API来针对简单用例。如果你维护一个HTTP客户端并且对此感兴趣,我非常愿意将Bof合并到现有的库中。打开一个问题!

安装

composer require mnapoli/bof

使用

$http = new Bof\Http;

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

配置

Bof\Http类是不可变的.

通过调用withXxx()方法应用配置,这些方法每次都会创建一个新的对象

$http = new Bof\Http;

// The header will apply to all subsequent requests
$http = $http->withHeader('Authorization', "Bearer $token");

记住,withXxx()方法返回原始客户端的副本

$http1 = new Bof\Http;

$http2 = $http1->withHeader('Authorization', "Bearer $token");

// $http1 does not have the header applied
// $http2 has the header

通过这种模式,可以使用相同的方法仅针对特定请求应用配置

$products = $http->withHeader('Authorization', "Bearer $token")
    ->get('https://example.com/api/products')
    ->getData();

// The next requests will *not* have the `Authorization` header

响应

响应符合PSR-7规范。它们还提供了便于处理JSON响应的方法

$http = new Bof\Http;

$products = $http->get('https://example.com/api/products')
    ->getData();

getData()方法将解码JSON响应。

所有PSR-7方法也都可用

$response = $http->get('https://example.com/api/products');
echo $response->getStatusCode();
echo $response->getHeader('Content-Length')[0];
echo $response->getBody()->getContents();

了解更多.

发送JSON数据

使用JSON方法,数据将自动编码为JSON。将添加Content-Type头为application/json

$http->postJson('https://example.com/api/products', [
    'foo' => 'bar',
]);
// putJson() or patchJson() works as well

发送表单数据

数据也可以以application/x-www-form-urlencoded POST请求的形式发送

$http->postForm('https://example.com/api/products', [
    'foo' => 'bar',
    'baz' => ['hi', 'there!'],
]);
// putForm() works as well

异常

无效的HTTP响应(状态码4xx或5xx)将抛出异常。

try {
    $http->get('https://example.com/api/products');
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
    // $e->getRequest()
    // $e->getResponse()
    ...
}

了解更多.

头部

$http = $http->withHeader('Authorization', "Bearer $token");

// Headers can have multiple values
$http = $http->withHeader('X-Foo', ['Bar', 'Baz']);

超时

默认情况下设置较短的超时时间

  • 请求超时为5秒
  • HTTP连接超时为3秒

你可以设置更短或更长的超时时间(或通过将它们设置为0来禁用它们)

// 2 seconds for the request timeout, 1 second for the connection timeout
$http = $http->withTimeout(2, 1);

查询字符串参数

你可以在请求的URI中设置查询字符串参数

$response = $http->get('http://httpbin.org?foo=bar');

你可以将查询字符串参数指定为一个数组

$http->withQueryParams(['foo' => 'bar'])
    ->get('http://httpbin.org');

以数组的形式提供选项将使用PHP的http_build_query函数来格式化查询字符串。

最后,你可以以字符串的形式提供查询请求选项。

$http->withQueryParams('foo=bar')
    ->get('http://httpbin.org');

代理

使用withSingleProxy()指定所有协议的代理

$http = $http->withSingleProxy('tcp://localhost:8125');

使用withMultipleProxies()指定HTTP和HTTPS的代理,以及不应代理的主机名列表

$http = $http->withMultipleProxies(
    'tcp://localhost:8125', // Use this proxy with HTTP 
    'tcp://localhost:9124', // Use this proxy with HTTPS
    ['.mit.edu', 'foo.com'] // Don't use a proxy with these
);

请注意,您可以提供包含方案、用户名和密码的代理URL。例如,http://username:password@192.168.16.1:10

Guzzle集成

Bof基于Guzzle。您甚至可以使用自己的Guzzle客户端,例如,如果您已经预先配置了它

$guzzleClient = new GuzzleHttp\Client([
    'base_uri' => 'http://httpbin.org',
    'timeout'  => 2.0,
]);

$http = new Bof\Http($guzzleClient);

了解更多.