5.2 Guzzle Http客户端
安装composer包
composer require hyperf/guzzle
配置
使用
<?php
namespace AppController;
class IndexController extends AbstractController
{
/**
* @HyperfDiAnnotationInject()
* @var HyperfGuzzleClientFactory
*/
protected $clientFactory;
public function index()
{
$options = [
// guzzle http里的配置信息
'base_uri' => 'http://127.0.0.1:8888',
'handler' => GuzzleHttpHandlerStack::create(new HyperfGuzzleCoroutineHandler()),
'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 AppController;
class IndexController extends AbstractController
{
/**
* @HyperfDiAnnotationInject()
* @var HyperfGuzzleClientFactory
*/
protected $clientFactory;
public function index()
{
$options = [
// guzzle http里的配置信息
'base_uri' => 'http://127.0.0.1:8888',
'handler' => (new HyperfGuzzleHandlerStackFactory())->create(),
'timeout' => 5,
// swoole的配置信息,内容会覆盖guzzle http里的配置信息
'swoole' => [
'timeout' => 10,
'socket_buffer_size' => 1024 * 1024 * 2,
],
];
$client = make(GuzzleHttpClient::class, [
'config' => $options
]);
$response = $client->get("/test");
return [
'code' => $response->getStatusCode(),
'body' => $response->getBody()->getContents(),
'content' => $response->getReasonPhrase()
];
}
}