如何使用 Guzzle 从 curl 发送 -d 标志

How to send -d flag from curl with Guzzle

我有以下 cURL 语句

curl http://localhost/ocpu/library/stats/R/t.test -d "x=x0e48e4cb3f&y=x09aaf63ea6"

当我在终端中 运行 时,一切都很好,我得到了我想要的响应,完成了计算。

现在我正尝试使用 Guzzle 将其构建到 PHP 应用程序中。我有以下代码。

$result = $this->client->request('POST', 'http://localhost/ocpu/library/stats/R/t.test', ['json'   => ["x" => $x, "y" => $y],
                                 'header' => ["content" => "application/x-www-form-urlencoded"]])->getBody();

$x 和 $y 包含带有 cURL 语句中 x 和 y 值的字符串。

这给了我错误“400 Bad Request 响应: 'x' 观察不足

使用 OpenCPU API Explorer 我发现在尝试通过在它们周围添加引号将 x 和 y 参数添加为原始字符串时我遇到了同样的错误。

所以我的问题似乎是 Guzzle 将 x 和 y 参数作为字符串而不是 Temp 键发送。

我怎样才能让它发送准确的 cURL 参数?

提前谢谢大家。

$params = [
    'x' => 'value',
    'y' => 'value',
];

$response = $client->post($uri, [
    'form_params' => $params,
]);

我认为问题出在您提供的代码示例中。当 'form_params' 是(我解释的)您正在寻找时,您正在使用 'json'。当使用'form_params'时,表单数据会自动设置content-typeheaders。

可以在 Guzzle 6 Request Options

中找到更多信息