phico / http-client
Phico 使用的 cURL 内置函数的简单包装器
dev-main
2024-08-04 11:50 UTC
Requires
- php: ^8.0
Requires (Dev)
- pestphp/pest: ^2.34
- phpstan/phpstan: *
This package is auto-updated.
Last update: 2024-09-04 12:04:38 UTC
README
这是一个简单封装内置 cURL 函数的 HTTP 客户端。
安装
通过 composer 安装
composer require phico/http-client
用法
制作请求
获取远程内容
使用 get()
请求页面,结果存储在响应的 body
中。
$response = http()->get('https://example.com'); echo $response->body;
将查询参数作为第二个参数发送
$response = http()->get('https://example.com/hello', [ 'cache' => false, 'name' => 'Bob' ]); echo $response->body;
支持所有 HTTP 方法
- GET
- POST
- DELETE
- PUT
- PATCH
- HEAD
- OPTIONS
可以通过 method()
使用自定义动词
$response = http()->method('PURGE', 'https://example.com/cache');
上传表单数据
$response = http() ->form([ 'user' => 'bob', 'password' => 't0p-secret' ])->post('https://example.com/signin');
附带文件
$response = http() ->form([ 'overwrite' => true, ]) ->file('/path/to/file') ->post('https://example.com/upload');
文件还可以接受可选的文件名和可选的 mime 类型。
$response = http() ->file('/path/to/invoice.pdf', 'invoice-2024.pdf') ->file('/path/to/readme.txt', 'read-me.txt', 'text/plain') ->post('https://example.com/upload');
上传 JSON 数据
$response = http() ->json([ 'colour' => 'Blue' ]) ->put('https://example.com/widgets/123');
响应
每个请求都返回一个包含请求、响应 cookies、headers、状态码和 body 的结构化响应。
$response = http() ->json([ 'colour' => 'Blue' ]) ->post('https://example.com/widgets/123'); echo $response->http_code; // 200, 401, 500 etc.. echo $response->body; echo join("\n", $response->cookies); // cookies array echo join("\n", $response->headers); // headers array // and weirdly var_dump($response->request);
错误处理
仅在连接或传输错误时抛出异常,您的代码应适当处理 HTTP 状态码。
try { $response = http() ->form([ 'user' => '', 'password' => 't0p-secret' ])->post('https://example.com/signin'); } catch (HttpClientException $e) { // show exception details echo $e->getSummary(); echo $e->getTraceAsString(); }