使用 Swoole Coroutine\Http\Client 发送 JSON 数据需设置 Content-Type 为 application/json,并用 json_encode 将数组转为 JSON 字符串作为请求体,通过 post() 或 put() 方法发送,确保服务器正确解析。
使用 Swoole 的 Coroutine\Http\Client 发送 JSON 数据,关键在于正确设置请求头 Content-Type 为 application/json,并将 PHP 数组或对象编码为 JSON 字符串作为请求体。
以下是一个完整的协程客户端发送 JSON 数据的示例:
use Swoole\Coroutine\Http\Client;
go(function () {
$client = new Client('127.0.0.1', 80);
// 要发送的 PHP 数据
$data = [
'name' => 'Alice',
'age' => 25,
'city' => 'Beijing'
];
// 设置请求头
$client->setHeaders([
'Content-Type' => 'application/json',
'User-Agent' => 'Swoole-Coroutine-Client/1.0'
]);
// 发起 POST 请求,第三个参数是请求体(JSON 格式)
$client->post('/api/u
ser', json_encode($data));
// 获取响应
echo $client->getBody();
$client->close();
});
如果你需要使用 PUT 方法发送 JSON 数据,方式类似:
$client->setHeaders([
'Content-Type' => 'application/json'
]);
$client->put('/api/user/123', json_encode([
'name' => 'Bob',
'status' => 'active'
]));
$client->errCode 判断是否发生网络错误。