olegv9 / http-client
小巧的cURL包装器
3.0.4
2021-03-31 06:41 UTC
README
composer require olegv9/http-client
用法
设置
use HttpClient\HttpClient; $http = new HttpClient();
HTTP方法
$url = 'https://example.com'; $response = $http->get($url)->text(); $response = $http->post($url, ['some' => 'data'])->text(); $response = $http->put($url, ['some' => 'data'])->text(); $response = $http->delete($url, ['some' => 'data'])->text();
响应处理
$text = $http->get($url)->text(); //raw text $object = $http->get($url)->json(); //json_decode() applied $array = $http->get($url)->json(true); //json_decode(true) applied
方法
$res = $http->get($url); $res->text(); //see above $res->json(); //see above //status code (200, 403, etc) $httpCode = $res->code(); //sending request error (network failure, invalid URL, etc) $error = $res->error(); //last URL after redirect chain (CURLINFO_EFFECTIVE_URL) $lastUrl = $res->getUrl(); //response header $header = $res->getHeader('Content-Type'); //all response headers list $allHeaders = $res->getAllHeaders(); //request time $time = $res->time();
选项
请求选项以关联数组的形式在GET请求的第二个参数中传递,在其他请求中传递第三个参数。
可用选项
- type - 请求类型 ("json", "urlencoded", "multipart")。默认 "urlencoded"。
- followRedirects - 是否需要执行重定向。默认为 true。
- maxRedirects - 最大重定向次数。默认为 10。
- ignoreSslErrors - 忽略损坏的SSL。默认为 false。
- timeout - 超时时间(秒)。默认为 40。
- auth - 格式为 "login:password" 的基本认证。
- headers - 头部信息的关联数组(见下例)。
- curlOpts - curl的原始选项。
示例
//авторизация + заголовки $opts = [ 'auth' => 'admin:NgjrP4n', 'headers' => [ 'X-Some-Header' => 'OK' ] ]; $http->get($url, $opts); //Отправка JSON'а $data = [ 'site' => 'somesite.com', 'se' => 197, 'prim' => true ]; $opts = [ 'timeout' => 10, 'type' => 'json' ]; $http->post($url, $data, $opts);
多cURL
示例
$urls = [ 'http://example.com', 'http://example.com/page', 'http://example.org' ]; $opts = ['timeout' => 10]; $results = $http->multiGet($urls, $opts); //или //$results = $http->multiRequest('POST', $urls, $postData, $opts); foreach ($results as $res) { echo $res->text(); //текст ответа. Доступные также все методы, описанные выше }
数组可以由URL组成,也可以由包含设置的关联数组组成。
$urls = [ 'http://example.com', 'http://example.com/send', [ 'method' => 'POST', 'url' => 'http://example.net', 'data' => ['a' => 123], 'opts' => ['timeout' => 20] ], 'http://example.org' ]; $http->multiRequest('GET', $urls);