有人知道用Guzzle发布JSON的正确方法吗?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

我从服务器得到一个内部服务器错误响应。它使用Chrome邮差工作。


当前回答

对于《Guzzle 5》,《Guzzle 6》和《Guzzle 7》,你是这样做的:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs

其他回答

$client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

对于《Guzzle 5》,《Guzzle 6》和《Guzzle 7》,你是这样做的:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs

对于Guzzle <= 4:

这是一个原始的post请求,所以把JSON放在body中解决了这个问题

$request = $this->client->post(
    $url,
    [
        'content-type' => 'application/json'
    ],
);
$request->setBody($data); #set body!
$response = $request->send();

解决方案$客户端->请求('POST',…

对于那些使用$client->请求的人,这是如何创建JSON请求的:

$client = new Client();
$res = $client->request('POST', "https://some-url.com/api", [
    'json' => [
        'paramaterName' => "parameterValue",
        'paramaterName2' => "parameterValue2",
    ]
    'headers' => [
    'Content-Type' => 'application/json',
    ]
]);

Guzzle JSON请求参考

简单而基本的方法(guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

为了获得响应状态代码和主体的内容,我这样做:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';