phppkg/http-client

PHP 的简单 HTTP 客户端库

v3.0.2 2023-01-11 05:25 UTC

This package is auto-updated.

Last update: 2024-09-02 03:15:36 UTC


README

License Php Version Latest Stable Version GitHub tag (latest SemVer) Github Actions Status

一个易于使用的 PHP HTTP 客户端库。支持 CURL、文件、fsockopen、流驱动。

  • 简单易用的 HTTP 客户端
  • 支持驱动:curl swoole fsockopen stream fopen
  • 支持所有 HTTP 方法。例如:GET,POST,PATCH,PUT,HEAD,DELETE
  • 支持设置代理、自定义头部、认证、内容类型等。
  • 实现接口 PSR 18

安装

composer require phppkg/http-client

使用

创建客户端实例

自动选择驱动类:

use PhpPkg\Http\Client\Client;

// use factory
$client = Client::factory([
    'driver' => 'curl', // stream, fsock, fopen, file, co, co2
    
    // ... 更多选项
    'baseUrl' =>  'http://my-site.com'
]);

直接使用指定的类:

$options = [
  'baseUrl' =>  'http://my-site.com'
  // ...
];
$client = CurlClient::create($options);
$client = FileClient::create($options);
$client = FSockClient::create($options);
$client = FOpenClient::create($options);
$client = CoClient::create($options);

基本使用

use PhpPkg\Http\Client\Client;

$client = Client::factory([]);

$client->get('/users/1');

$post = ['name' => 'john'];
$client->post('/users/1', $post);

// add ajax header
$client->byAjax()->post('/users/1', $post);

// add json content type
$client->json('/users/1', json_encode($post));
// or
$client->byJson()->post('/users/1', json_encode($post));

$statusCode = $client->getStatusCode();
$headers = $client->getResponseHeaders();

// get body data
$data = $client->getResponseBody();
$array = $client->getArrayData();

解析响应 Body:

$data = $client->getDataObject();
$data->getInt('createTime', 0);

$user = new User();
$client->bindBodyTo($user);
vdump($user->name);

文件上传下载

  • public function upload(string $url, string $field, string $filePath, string $mimeType = '')
  • public function download(string $url, string $saveAs)
  • public function downloadImage(string $imgUrl, string $saveDir, string $rename = '')
$client = CurlClient::create([
  // ...
]);

$client->upload(...);

常用方法

  • getJsonArray/getArrayData(): array
  • getJsonObject(): stdClass
  • getDataObject(): DataObject
  • bindBodyTo(object $obj): void

许可证

MIT