elfsundae / httpclient
一个智能的Guzzle包装器,提供方便的方法链式调用、全局请求选项和魔法方法来自定义请求选项。
2.2.0
2022-02-19 20:33 UTC
Requires
- php: >=5.6.4
- guzzlehttp/guzzle: ~6.3|~7.0
- illuminate/support: ~5.0|~6.0|~7.0|~8.0|~9.0
Requires (Dev)
- dms/phpunit-arraysubset-asserts: ^0.4.0
- mockery/mockery: ~1.0
- phpunit/phpunit: ~5.7|~6.0|~7.0|~8.0|~9.0
README
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', ]);
此外,您还可以使用header
、accept
、acceptJson
、userAgent
或contentType
来设置请求头
$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许可证。