协程 HTTP 客户端用来在服务端调外部接口,非阻塞,不要用 curl_exec(会卡住整个进程)。
用法
use houze\client\Http;
$http = new Http();
// GET
$res = $http->get('https://api.example.com/list', ['page' => 1]);
// POST
$res = $http->post('https://api.example.com/create', ['title' => 'demo']);
// 状态与错误
$http->statusCode(); // HTTP 状态码
$http->errCode(); // 传输层错误码(0 表示无错)
$http->body(); // 响应体
$http->headers(); // 响应头
常用设置
$http->domain('https://api.example.com') // 统一域名,后面只写路径
->header(['Authorization' => 'Bearer xxx'])
->proxy('http://127.0.0.1:1080') // 走代理
->timeout(3); // 超时(秒)
返回值怎么判
$res = $http->get('/api/list');
if ($http->errCode() !== 0) {
return $this->api(502, '上游不可达:' . $http->errCode());
}
$data = json_decode($res, true);
if (!is_array($data)) {
return $this->api(502, '上游返回非 JSON');
}
注意
- 必须设超时。默认超时可能很长,一个慢接口能把请求协程拖死;
- 协程客户端不读系统
http_proxy环境变量,要代理就显式proxy(); - 大文件下载用
download()落盘,别整个读进内存。