Question:
How do I correctly send a POST request with JSON data using Guzzle? The code below results in an internal server error response:
$request = $this->client->post(self::URL_REGISTER, [ 'content-type' => 'application/json', ], [json_encode($_POST)]);
Answer:
Using Guzzle version 5 or later, you can send JSON data in a POST request as follows:
use GuzzleHttp\Client; $client = new Client(); // Use GuzzleHttp\RequestOptions::JSON $response = $client->post('url', [ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'], ]); // or use 'json' $response = $client->post('url', [ 'json' => ['foo' => 'bar'], ]);
The Guzzle documentation provides more details on JSON request options.
The above is the detailed content of How to POST JSON Data Using Guzzle?. For more information, please follow other related articles on the PHP Chinese website!