You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP GuzzleHttp发送JSON POST请求?(Guzzle 6.0+)

正确用GuzzleHttp发送JSON POST请求的方法

嘿,我来帮你搞定这个Guzzle发送JSON POST请求的问题!在Guzzle 6.0+版本里,其实有更简洁且不易出错的方式来发送JSON请求,不用手动拼接JSON字符串或者反复检查请求头。

推荐实现方式:使用json选项

Guzzle专门提供了json配置项,你只需要传入请求体对应的PHP数组,它会自动帮你完成JSON编码和设置Content-Type: application/json请求头,省心又靠谱。下面是完整的示例代码:

use GuzzleHttp\Client;

// 初始化Guzzle客户端
$client = new Client();

try {
    // 发送POST请求
    $response = $client->post('替换成你的目标API地址', [
        'headers' => [
            'Referer' => 'https://www.rituals.com/es-es/stores'
            // 无需手动设置Content-Type,Guzzle会自动添加
        ],
        'json' => [
            'latitude' => '',
            'longitude' => '',
            'countryCode' => 'ES',
            'filterPostalCode' => '',
            'filterCity' => '',
            'filterCountryCode' => 'ES',
            'searchText' => '',
            'nextPageToken' => 0,
            'storeType' => 'normal',
            'checkStoreAvailability' => false
        ]
    ]);

    // 获取并处理响应内容
    $responseBody = $response->getBody()->getContents();
    $responseData = json_decode($responseBody, true);

    // 这里可以根据业务逻辑处理返回的数据
    var_dump($responseData);
} catch (\GuzzleHttp\Exception\RequestException $e) {
    // 捕获请求异常(比如网络错误、HTTP状态码错误等)
    echo "请求失败:" . $e->getMessage();
    if ($e->hasResponse()) {
        echo "<br>错误响应内容:" . $e->getResponse()->getBody()->getContents();
    }
}

如果你坚持手动处理请求体(不推荐)

要是你想沿用手动设置body的方式,记得要自己把PHP数组编码成JSON字符串,同时确保Content-Type请求头正确设置,示例如下:

$client->post('替换成你的目标API地址', [
    'headers' => [
        'Content-Type' => 'application/json',
        'Referer' => 'https://www.rituals.com/es-es/stores'
    ],
    'body' => json_encode([
        'latitude' => '',
        'longitude' => '',
        'countryCode' => 'ES',
        'filterPostalCode' => '',
        'filterCity' => '',
        'filterCountryCode' => 'ES',
        'searchText' => '',
        'nextPageToken' => 0,
        'storeType' => 'normal',
        'checkStoreAvailability' => false
    ])
]);

这种方式需要自己维护JSON编码和请求头,容易出现编码错误或者遗漏请求头的问题,所以更推荐第一种用json选项的方式。

内容的提问来源于stack exchange,提问作者Cristian Gonzalez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:22:30