使用 PHP Guzzle HTTP 6 发送 JSON 和已经编码的数据

Using PHP Guzzle HTTP 6 to send JSON with data that is already encoded

我正在尝试发送一个 POST 请求,其中包含带有以下 header 的原始 JSON 字符串:Content-Type: application/json.

通过查看文档,我发现我可以做这样的事情...

$data = ['x' => 1, 'y' => 2, 'z' => 3];
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'json' => $data,
];
$client->post('http://example.com', $options);

我的问题是,当我走到这一步时,$data 已经 json_encode 了。

我已经尝试了以下但它不起作用。

$data = json_encode(['x' => 1, 'y' => 2, 'z' => 3]);
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'body' => $data,
    'headers' => ['Content-Type' => 'application/json'],
];
$client->post('http://example.com', $options);

我的问题是:我可以将 json 选项与 already-encoded 数组一起使用吗?或者有没有办法让我简单地设置 Content-Type header?

根据 guzzle 的文档 http://docs.guzzlephp.org/en/latest/request-options.html#json

可以将已经编码好的json直接传入body参数

Note This request option does not support customizing the Content-Type header or any of the options from PHP's json_encode() function. If you need to customize these settings, then you must pass the JSON encoded data into the request yourself using the body request option and you must specify the correct Content-Type header using the headers request option.

This option cannot be used with body, form_params, or multipart

Guzzle 还提供 json Request option 将自动对您的内容进行编码并设置 Content-Type header。更多信息请见 link。事实上,提供的示例使用了 PUT 请求。

$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);