问题
I am trying to send a POST request which contains a raw JSON string with the following header: Content-Type: application/json
.
From looking at the docs, I can see that I can do something like this...
$data = ['x' => 1, 'y' => 2, 'z' => 3];
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
'json' => $data,
];
$client->post('http://example.com', $options);
My problem is that when I get to this point, $data
has already been json_encode
'd.
I have tried the following but it does not work.
$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);
My question is: can I use the json
option with an already-encoded array? Or is there a way for me to simply set the Content-Type
header?
回答1:
According to guzzle's docs http://docs.guzzlephp.org/en/latest/request-options.html#json
You can pass the already encoded json directly into the body parameter
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
回答2:
Guzzle also provides the json
Request option which will automatically encode your content and set the Content-Type
header. More information at the link. In fact the example provided uses a PUT request.
$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);
来源:https://stackoverflow.com/questions/36697724/using-php-guzzle-http-6-to-send-json-with-data-that-is-already-encoded