rexlabs/hyper-http

4.0.0 2023-07-20 04:58 UTC

This package is auto-updated.

Last update: 2024-09-20 07:17:21 UTC


README

这个库不在积极开发中。

请考虑使用guzzlehttp/guzzle或其他库。

仅修复bug。

Hyper HTTP客户端

License: MIT Packagist

概述

Hyper是一个HTTP客户端,旨在提供一个简单但强大的接口来执行HTTP调用和检索以及操作API数据。

为什么使用Hyper

  • 极其简单的接口 Hyper::get('http://some/url')
  • 还支持对象风格 Hyper::make(...)->get('http://some/url')
  • 提供了一个Response对象,该对象提供了有用的信息,如HTTP状态码、正文和头信息。
  • 每个Response都混入了rexlabs\array-object,这使得您可以轻松查询API响应。
  • 当发生错误时,会抛出有限的一组异常(可以访问请求和/或响应)。
  • 您可以通过$response->getRequest()访问原始的Request
  • 支持所有Guzzle客户端功能,包括流。
  • 允许您从命令行生成cURL请求以重现请求。
  • 轻松记录所有请求

用法

<?php
use Rexlabs\HyperHttp\Hyper;

$response = Hyper::get('http://openlibrary.org/subjects/love.json');

// The first book for 'love' is: Wuthering Heights
echo "The first book for '{$response->name}' is: {$response->works->first()->title}\n";

echo "Total works: {$response->works->count()} books\n";

安装

在您的项目中安装

composer require rexlabs/hyper-http

示例

所有RESTful方法都返回一个Response对象,这使得与响应交互变得简单。

示例:使用静态方法

<?php
use Rexlabs\HyperHttp\Hyper;

$response = Hyper::get('https://example.com/url');
echo 'Status Code: '.$response->getStatusCode()."\n";
echo (string)$response; // Output the response body

示例:与JSON API一起工作

由于响应混入了ArrayObject,您可以轻松从响应中检索和操作值

<?php
use Rexlabs\HyperHttp\Hyper;

// Fetch historical price via CryptoCompare's public API for Ethereum
$response = Hyper::get('https://min-api.cryptocompare.com/data/pricehistorical', [
    'fsym' => 'ETH',
    'tsyms' => 'BTC,USD',
    'ts' => '1452680400',
]);

// Output prices
printf("ETH->USD: %s\n", $response->get('ETH.USD'));
printf("ETH->BTC: %s\n", $response->get('ETH.BTC'));

示例:设置全局头信息和传递一个记录器

使用make()简化实例化,然后为未来的请求设置对象

<?php
use Rexlabs\HyperHttp\Hyper;
use Rexlabs\Logger\CustomLogger;

$hyper = Hyper::make()
    ->setBaseUri('http://example.com/api/v1')
    ->setHeader('X-App-Identity', 'Some App')
    ->setHeader('X-Correlation-Id', '12345')
    ->setLogger(new CustomLogger);
  • $hyper = Hyper::make(array $config = [], \GuzzleHttp\Client $guzzle, \Psr\Log\LoggerInterface $logger)

示例:通过构造函数实例化

为了完全控制实例化,请使用构造函数并传入一个Guzzle实例

<?php
use Rexlabs\HyperHttp\Client;
use GuzzleHttp\Client as GuzzleClient;
use Psr\Log\NullLogger;

$hyper = new Client(new GuzzleClient(), new NullLogger(), [
   'base_uri' => 'http://example.com/api/v1',
   'headers' => [
       'X-App-Identity' => 'Some App',
   ],
]);
$response = $hyper->get('/messages');

示例:转储cURL请求

您可以从命令行轻松生成一个cURL请求以重现您的最后一个请求

<?php
use Rexlabs\HyperHttp\Hyper;

echo Hyper::get('https://example.com/api/v1/resources')
    ->getCurlRequest();

输出

curl \
  'https://min-api.cryptocompare.com/data/pricehistorical?fsym=ETH&tsyms=BTC%2CUSD&ts=1452680400&extraParams=your_app_name' \
  -H 'Content-Type: application/json' -H 'Accept: application/json'

HTTP方法

Hyper提供了以下方法来与远程端点交互

get()

get(mixed $uri, array $query = [], array $headers = [], array $options = []): Response

发送HTTP GET请求并返回响应

$response = Hyper::get('https://example.com', ['sort' => 'latest'], ['X-Greeting' => 'Hello!']);

$response = $hyper->get('/v1/people');
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $query是一个可选的查询参数数组,它将被附加到URI。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

post()

post(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response

发送HTTP POST请求并返回响应

$response = Hyper::post('https://example.com/fruit', 'apples');

$response = $hyper->post('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $body是有效载荷。如果您提供一个数组,它将被转换并作为JSON传输。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

其他方法

  • $response = $hyper->postForm($uri, $formParams, $headers, $options);
  • $response = $hyper->postMultipartForm($uri, $formParams, $headers, $options);

put()

put(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response

发送HTTP PUT请求,并返回响应

$response = Hyper::put('https://example.com/fruit', 'apples');

$response = $hyper->put('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $body是有效载荷。如果您提供一个数组,它将被转换并作为JSON传输。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

patch()

patch(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response

发送HTTP PATCH请求,并返回响应

$response = Hyper::patch('https://example.com/fruit', 'apples');

$response = $hyper->patch('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $body是有效载荷。如果您提供一个数组,它将被转换并作为JSON传输。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

delete()

delete(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response

发送HTTP DELETE请求,并返回响应

$response = Hyper::delete('https://example.com/fruit', 'apples');

$response = $hyper->delete('/v1/people/1');
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $body是可选的有效负载。如果您提供数组,它将被转换为json并发送。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

call()

call(string $method, mixed $uri, mixed $body, array $headers, array $options): Response

通过指定第一个参数为method来发送通用的HTTP请求。

// Statically
$response = Hyper::call('MOVE', 'myfile1234', ['new_location' => 'some_folder']);

// Http method verbs may also be invoked via method name
$response = Hyper::move('myfile1234', ['new_location' => 'some_folder']);
$response = Hyper::somethingelse(...);

// Via object
$response = $hyper->call('MOVE', 'myfile1234', ['new_location' => 'some_folder']);
  • $method是HTTP动词。例如,GET或标准之外的内容。
  • $uri是一个字符串或一个Uri。如果字符串不是绝对路径,它将被附加到基本URI。
  • $body是可选的有效负载。如果您提供数组,它将被转换为json并发送。
  • $headers是一个可选的头信息数组(按头名称索引),它将与任何全局头信息合并。
  • $options是一个可选的Guzzle客户端选项数组。

请求方法

来自Rexlabs\HyperHttp\Message\Request对象的可用方法

getUri()

返回封装此请求URI/URL的UriInterface对象。

getMethod()

返回此请求的HTTP方法动词。

getHeaders()

返回此Request的头部数组。

getCurl()

返回适用于在命令行中运行的cURL请求(字符串)。用于调试请求。

响应方法

来自Rexlabs\HyperHttp\Message\Response对象的可用方法

getRequest()

返回与Response关联的Rexlabs\HyperHttp\Message\Request对象。

getCurlRequest()

返回适用于在命令行中运行的cURL请求(字符串)。用于调试请求。

getStatusCode()

返回此Response的HTTP状态码。例如,200。

getReasonPhrase()

返回与状态码关联的HTTP原因短语。例如,“OK”。

isJson()

如果这是JSON响应,则返回true

toArray()

将JSON响应转换为数组并返回该数组。

toObject()

将JSON响应转换为ArrayObject

ArrayObject

每个Response对象都具有rexlabs\array-object包中的ArrayObject类的所有方法和功能。

这意味着基于以下响应有效负载

{
  "books": [
    {
      "id": 1,
      "title": "1984",
      "author": "George Orwell"
    },
    {
      "id": 2,
      "title": "Pride and Prejudice",
      "author": "Jane Austen"
    }
  ]
}

您可以执行以下功能

$response->books; // Instance of ArrayObject
$response->books->pluckArray('author'); // array [ 'George Orwell', 'Jane Austen' ]
$response->pluckArray('books.author'); // array [ 'George Orwell', 'Jane Austen' ]
$response->books->count(); // 2
$response->books->isCollection(); // true
$response->books[0]; // Instance of ArrayObject
$response->books[0]->isCollection(); // false
$response->books[0]->id; // 1
$response->get('books.1.title');    // "Pride and Prejudice"
foreach ($response->books as $book) {
    echo "{$book->title} by {$book->author}\n";
}

您还可以调用

$obj = $response->toObject();   // Instance of Arraybject

配置

设置所有客户端的默认配置(默认为[])

Hyper::setDefaultConfig($config);

为此客户端设置配置(值将覆盖/与默认值合并)

$client = Hyper::make($config);

默认日志记录器

设置所有未提供日志记录器的客户端使用的默认日志记录器。
必须实现LoggerInterface(默认为NullLogger

Hyper::setDefaultLogger($logger);

记录Curl

记录所有请求的cURL字符串(需要设置日志记录器)

$config = [
    'log_curl' => true,
];

Guzzle配置

设置传递给底层GuzzleClient的配置

$config = [
    'guzzle' => [
        'verify' => false,
    ],
];

// Set for all clients
Hyper::setDefaultConfig($config);

// Set for one client
$client = Hyper::make($config);

测试

运行测试

composer tests

运行覆盖率报告

composer coverage

覆盖率报告输出到./tests/report/index.html

扩展

Hyper允许通过以下方式扩展自定义客户端

  • 为Hyper的每个子类存储单独的实例以供静态使用
    • 静态使用MyHyperSubclass将返回由MyHyperSubclass创建的正确实例
    • 静态使用Hyper将返回由Hyper创建的正确实例
  • 覆盖protected static function makeClient以自定义客户端类(例如,将new Client替换为new MyClient
  • 覆盖protected static function makeConfig以自定义默认客户端配置
  • 覆盖protected static function makeGuzzleConfig以自定义默认Guzzle客户端
  • 覆盖protected static function getBaseUri以向客户端提供默认base_uri

贡献

欢迎贡献,请提交拉取请求或创建一个问题。您提交的代码应使用PSR-1/PSR-2标准格式化。

关于

  • 作者:Jodie Dunlop
  • 许可证:MIT
  • 版权所有(c)2018 Rex Software Pty Ltd