Guzzle HTTP 客户端快速入门指南
什么是 Guzzle?
Guzzle 是一个强大的 PHP HTTP 客户端,用于发送 HTTP 请求并与 Web 服务交互。它提供了简单易用的接口,支持同步和异步请求,并内置了许多实用功能如请求重试、连接池、中间件等。
安装 Guzzle
在开始使用 Guzzle 前,请确保已通过 Composer 安装。这里我们主要关注使用方式,安装步骤略过。
创建 HTTP 客户端
Guzzle 的核心是 Client
类,它是不可变对象,一旦创建就不能修改其配置。
use GuzzleHttp\Client;
$client = new Client([
// 基础 URI 用于相对路径请求
'base_uri' => 'http://httpbin.org',
// 设置默认请求选项
'timeout' => 2.0,
]);
基础 URI 解析规则
base_uri
选项遵循 RFC 3986 规范,以下是常见情况示例:
| base_uri | URI | 结果 | |-----------------------|-----------|--------------------------| | http://foo.com
| /bar
| http://foo.com/bar
| | http://foo.com/foo
| bar
| http://foo.com/bar
| | http://foo.com/foo/
| bar
| http://foo.com/foo/bar
|
发送请求
同步请求
Guzzle 提供了便捷方法发送各种 HTTP 请求:
$response = $client->get('http://httpbin.org/get');
$response = $client->post('http://httpbin.org/post');
// 其他方法:delete, head, options, patch, put
也可以先创建请求对象再发送:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
异步请求
异步请求不会阻塞程序执行:
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->postAsync('http://httpbin.org/post');
// 其他异步方法...
处理异步响应:
$promise->then(
function ($response) {
echo $response->getStatusCode();
},
function ($exception) {
echo $exception->getMessage();
}
);
并发请求
Guzzle 支持高效的并发请求处理:
use GuzzleHttp\Promise;
$promises = [
'image' => $client->getAsync('/image'),
'png' => $client->getAsync('/image/png')
];
$responses = Promise\Utils::unwrap($promises);
echo $responses['image']->getHeader('Content-Length')[0];
对于大量不确定数量的请求,可以使用 Pool:
use GuzzleHttp\Pool;
$requests = function ($total) {
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', 'http://example.com');
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
// 成功回调
},
'rejected' => function ($reason, $index) {
// 失败回调
},
]);
$pool->promise()->wait();
处理响应
响应对象实现了 PSR-7 的 ResponseInterface
接口:
$code = $response->getStatusCode(); // 状态码
$reason = $response->getReasonPhrase(); // 状态描述
// 获取头部信息
if ($response->hasHeader('Content-Length')) {
echo $response->getHeader('Content-Length')[0];
}
// 处理响应体
$body = $response->getBody();
echo $body; // 直接输出
$stringBody = (string) $body; // 转为字符串
$tenBytes = $body->read(10); // 读取10字节
请求参数设置
查询字符串
三种方式设置查询参数:
// 直接在URL中
$client->get('http://httpbin.org?foo=bar');
// 使用数组
$client->get('http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
// 使用字符串
$client->get('http://httpbin.org', ['query' => 'foo=bar']);
上传数据
原始数据上传
// 字符串数据
$client->post('http://httpbin.org/post', ['body' => 'raw data']);
// 文件流
$body = fopen('/path/to/file', 'r');
$client->post('http://httpbin.org/post', ['body' => $body]);
// JSON数据
$client->put('http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
表单提交
普通表单:
$client->post('http://httpbin.org/post', [
'form_params' => [
'field_name' => 'value',
'nested' => ['key' => 'value']
]
]);
文件上传表单:
$response = $client->post('http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_field',
'contents' => fopen('/path/to/file', 'r'),
'filename' => 'custom_name.txt'
]
]
]);
Cookies 管理
Guzzle 提供了完善的 Cookie 支持:
// 使用特定 CookieJar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$client->get('http://httpbin.org/cookies', ['cookies' => $jar]);
// 客户端共享 Cookie
$client = new Client(['cookies' => true]);
重定向控制
默认跟随最多5次重定向:
// 禁用重定向
$response = $client->get('http://github.com', [
'allow_redirects' => false
]);
// 自定义重定向设置
$response = $client->get('http://example.com', [
'allow_redirects' => [
'max' => 10, // 最多10次重定向
'strict' => true // 严格遵循RFC标准
]
]);
异常处理
Guzzle 的异常体系结构如下:
RuntimeException
└── TransferException
├── ConnectException (网络错误)
└── RequestException
├── BadResponseException
│ ├── ServerException (5xx错误)
│ └── ClientException (4xx错误)
└── TooManyRedirectsException
通过捕获这些异常可以处理各种请求错误情况。
总结
Guzzle 提供了强大而灵活的 HTTP 客户端功能,从简单的 GET 请求到复杂的并发处理都能轻松应对。其符合 PSR-7 标准的实现也使其能很好地与现代 PHP 框架集成。通过本指南,您应该已经掌握了 Guzzle 的核心用法,可以开始在项目中实践了。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考