本文目录导读:

我来详细介绍在PHP项目中使用Guzzle HTTP客户端的方法。
安装Guzzle
首先通过Composer安装:
composer require guzzlehttp/guzzle
基本使用
创建客户端
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; // 创建客户端实例 $client = new Client();
发送GET请求
// 简单GET请求
$response = $client->get('https://api.example.com/users');
// 获取响应内容
$body = $response->getBody()->getContents();
$statusCode = $response->getStatusCode();
// 带查询参数的GET请求
$response = $client->get('https://api.example.com/users', [
'query' => [
'page' => 1,
'limit' => 10,
'sort' => 'name'
]
]);
// 带请求头的GET请求
$response = $client->get('https://api.example.com/users', [
'headers' => [
'Authorization' => 'Bearer your-token',
'Accept' => 'application/json'
]
]);
发送POST请求
// JSON数据
$response = $client->post('https://api.example.com/users', [
'json' => [
'name' => '张三',
'email' => 'zhangsan@example.com',
'age' => 25
]
]);
// 表单数据
$response = $client->post('https://api.example.com/login', [
'form_params' => [
'username' => 'admin',
'password' => '123456'
]
]);
// multipart/form-data(文件上传)
$response = $client->post('https://api.example.com/upload', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen('/path/to/file.jpg', 'r'),
'filename' => 'file.jpg'
],
[
'name' => 'description',
'contents' => '图片描述'
]
]
]);
处理响应
$response = $client->get('https://api.example.com/users');
// 获取状态码
$statusCode = $response->getStatusCode(); // 200
// 获取响应头
$headers = $response->getHeaders();
$contentType = $response->getHeaderLine('Content-Type');
// 获取响应体
$body = $response->getBody()->getContents(); // 原始字符串
// 解析JSON响应
$data = json_decode($response->getBody(), true);
// 检查状态码
if ($response->getStatusCode() == 200) {
echo "请求成功!";
} elseif ($response->getStatusCode() == 404) {
echo "资源未找到!";
}
错误处理
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\ConnectException;
try {
$response = $client->get('https://api.example.com/users/999');
} catch (ClientException $e) {
// 4xx 错误
echo "客户端错误:" . $e->getMessage();
$response = $e->getResponse();
echo $response->getStatusCode(); // 404, 401等
} catch (ServerException $e) {
// 5xx 错误
echo "服务器错误:" . $e->getMessage();
} catch (ConnectException $e) {
// 连接错误
echo "连接失败:" . $e->getMessage();
}
高级配置
基础认证
$client = new Client([
'base_uri' => 'https://api.example.com/',
'auth' => ['username', 'password'] // 基础认证
]);
// 或者
$response = $client->get('/users', [
'auth' => ['username', 'password']
]);
超时设置
$client = new Client([
'timeout' => 30.0, // 请求超时时间(秒)
'connect_timeout' => 5.0, // 连接超时时间(秒)
'read_timeout' => 10.0 // 读取超时时间(秒)
]);
代理设置
$client = new Client([
'proxy' => 'http://localhost:8080',
'verify' => false // 关闭SSL验证(不推荐生产环境)
]);
Cookie处理
use GuzzleHttp\Cookie\CookieJar;
// 创建CookieJar
$cookieJar = new CookieJar();
// 发送请求并保存Cookie
$response = $client->get('https://example.com/login', [
'cookies' => $cookieJar
]);
// 使用保存的Cookie发送后续请求
$response = $client->get('https://example.com/dashboard', [
'cookies' => $cookieJar
]);
异步请求
use GuzzleHttp\Promise;
// 发起多个异步请求
$promises = [
'users' => $client->getAsync('https://api.example.com/users'),
'posts' => $client->getAsync('https://api.example.com/posts'),
'comments' => $client->getAsync('https://api.example.com/comments')
];
// 等待所有请求完成
$results = Promise\Utils::unwrap($promises);
// 处理结果
foreach ($results as $key => $response) {
$data = json_decode($response->getBody(), true);
echo "$key 请求成功,数据量:" . count($data) . "\n";
}
完整示例:REST API客户端
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
class ApiClient
{
private $client;
private $baseUrl;
private $apiKey;
public function __construct($baseUrl, $apiKey)
{
$this->baseUrl = $baseUrl;
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => $baseUrl,
'timeout' => 30.0,
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
]);
}
public function getUsers($page = 1, $limit = 10)
{
try {
$response = $this->client->get('/api/users', [
'query' => [
'page' => $page,
'limit' => $limit
]
]);
return json_decode($response->getBody(), true);
} catch (ClientException $e) {
return [
'error' => true,
'message' => $e->getMessage(),
'status' => $e->getResponse()->getStatusCode()
];
} catch (ServerException $e) {
return [
'error' => true,
'message' => '服务器错误',
'status' => 500
];
}
}
public function createUser($userData)
{
try {
$response = $this->client->post('/api/users', [
'json' => $userData
]);
return json_decode($response->getBody(), true);
} catch (ClientException $e) {
$errors = json_decode($e->getResponse()->getBody(), true);
return [
'error' => true,
'message' => '创建用户失败',
'errors' => $errors
];
}
}
public function updateUser($id, $userData)
{
try {
$response = $this->client->put("/api/users/{$id}", [
'json' => $userData
]);
return json_decode($response->getBody(), true);
} catch (ClientException $e) {
return [
'error' => true,
'message' => $e->getMessage()
];
}
}
public function deleteUser($id)
{
try {
$response = $this->client->delete("/api/users/{$id}");
return [
'success' => true,
'message' => '用户删除成功'
];
} catch (ClientException $e) {
return [
'error' => true,
'message' => '删除用户失败'
];
}
}
}
// 使用示例
$api = new ApiClient('https://api.example.com', 'your-api-key');
// 获取用户列表
$users = $api->getUsers(1, 20);
print_r($users);
// 创建新用户
$newUser = $api->createUser([
'name' => '李四',
'email' => 'lisi@example.com'
]);
print_r($newUser);
性能优化建议
- 复用客户端实例:尽量复用
Client实例 - 使用连接池:默认支持连接池
- 异步请求:并发多个请求时使用异步
- 设置合理超时:避免长时间等待
- 启用HTTP Keep-Alive:减少连接建立开销
Guzzle是PHP中最流行的HTTP客户端之一,功能强大且易于使用,非常适合处理各种HTTP请求场景。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播