5.2 Guzzle Http客户端
安装composer包
composer require hyperf/guzzle
配置
- 在实例化客户端的时候以参数的方式做配置
- 参数均来自于 Guzzle Http文档里的配置信息
使用
<?php
namespace App\Controller;
class IndexController extends AbstractController
{
/**
* @\Hyperf\Di\Annotation\Inject()
* @var \Hyperf\Guzzle\ClientFactory
*/
protected $clientFactory;
public function index()
{
$options = [
// guzzle http里的配置信息
'base_uri' => 'http://127.0.0.1:8888',
'handler' => \GuzzleHttp\HandlerStack::create(new \Hyperf\Guzzle\CoroutineHandler()),
'timeout' => 5,
// swoole的配置信息,内容会覆盖guzzle http里的配置信息
'swoole' => [
'timeout' => 10,
'socket_buffer_size' => 1024 * 1024 * 2,
],
];
$client = $this->clientFactory->create($options);
$response = $client->get("/test");
return [
'code' => $response->getStatusCode(),
'body' => $response->getBody()->getContents(),
'content' => $response->getReasonPhrase()
];
}
}
输出
{
"code": 200,
"body": "{\"key\":\"value\"}",
"content": "OK"
}
使用(使用连接池)
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
class IndexController extends AbstractController
{
/**
* @\Hyperf\Di\Annotation\Inject()
* @var \Hyperf\Guzzle\ClientFactory
*/
protected $clientFactory;
public function index()
{
$options = [
// guzzle http里的配置信息
'base_uri' => 'http://127.0.0.1:8888',
'handler' => (new \Hyperf\Guzzle\HandlerStackFactory())->create(),
'timeout' => 5,
// swoole的配置信息,内容会覆盖guzzle http里的配置信息
'swoole' => [
'timeout' => 10,
'socket_buffer_size' => 1024 * 1024 * 2,
],
];
$client = make(\GuzzleHttp\Client::class, [
'config' => $options
]);
$response = $client->get("/test");
return [
'code' => $response->getStatusCode(),
'body' => $response->getBody()->getContents(),
'content' => $response->getReasonPhrase()
];
}
}文档更新时间: 2021-09-24 18:14 作者:赵豪