我正在尝试发送一个POST请求,其中包含带有以下标头的原始
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’d.
我尝试了以下但它不起作用.
$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选项与已编码的数组一起使用吗?或者我有办法简单地设置Content-Type标题吗?
最佳答案 根据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