elfsundae/httpclient

一个智能的Guzzle包装器,提供方便的方法链式调用、全局请求选项和魔法方法来自定义请求选项。

2.2.0 2022-02-19 20:33 UTC

This package is auto-updated.

Last update: 2024-09-20 02:38:50 UTC


README

Latest Version on Packagist Software License tests StyleCI SymfonyInsight Grade Quality Score Code Coverage Total Downloads

HttpClient是一个智能的Guzzle包装器,提供方便的方法链式调用、全局请求选项和魔法方法来自定义请求选项

安装

$ composer require elfsundae/httpclient

使用

use ElfSundae\HttpClient;

获取响应内容

$html = (new HttpClient)->fetchContent('http://httpbin.org');

$data = (new HttpClient)->fetchJson('https://httpbin.org/ip');

发起请求

$client = HttpClient::create('https://httpbin.org')
    ->catchExceptions(true)
    ->httpErrors(false)
    ->auth(['user', 'passwd']);

$query = $client->query(['foo' => 'bar'])->getJson('/get');

$form = $client->formParams(['foo' => 'bar'])->postJson('/post');

$json = $client->json(['foo' => 'bar'])->putJson('/put');

$download = $client->saveTo('image.png')->get('/image/png');

$file = fopen('image.png', 'r');
$uploadBody = $client->body($file)->postJson('/post');

$multipart = [
    'foo' => 'bar',
    'file' => $file,
    'image' => [
        'contents' => fopen('image.png', 'r'),
        'filename' => 'filename.png',
    ],
];
$formData = $client->multipart($multipart)->postJson('/post');

异步请求

$promise = $client->json($data)->getAsync('/get');

$promise = $client->formParams($data)->postAsync('/post');

应用请求选项

使用option方法

$client
    ->option('cert', $cert)
    ->option([
        'debug' => true,
        'headers.Content-Type' => 'application/json',
    ]);

或者使用客户端上的任何选项名的camelCase作为方法

$client
    ->allowRedirects(false)
    ->timeout(20)
    ->cookies($cookieJar)
    ->headers([
        'X-Foo' => 'foo',
    ]);

此外,您还可以使用headeracceptacceptJsonuserAgentcontentType来设置请求头

$client
    ->header('X-Foo', 'foo');
    ->header('X-Bar', 'bar');
    ->acceptJson()
    ->contentType('text/plain')
    ->userAgent('HttpClient/2.0')

全局默认请求选项

静态方法setDefaultOptions可用于为每个新的客户端实例配置默认选项

HttpClient::setDefaultOptions([
    'catch_exceptions' => true,
    'http_errors' => false,
    'connect_timeout' => 5,
    'timeout' => 20,
    'headers.User-Agent' => 'HttpClient/2.0',
]);

捕获Guzzle异常

catchExceptions方法确定是否捕获Guzzle异常

$response = $client->catchExceptions(true)->get('/api/path');

try {
    $response = $client->catchExceptions(false)->get('/api/path');
} catch (Exception $e) {
    // ...
}

测试

$ composer test

许可证

此包是开源软件,许可协议为MIT许可证