如何发送' list'使用Guzzle时json请求?

时间:2016-05-26 07:42:48

标签: php json guzzle

我正在使用Guzzle为服务器编写php sdk,我想用Guzzle发送http json这样的身体:

["test_1","test_2"]

但是当我编写这段代码时,我得到了错误的json:

$body = array(
    'test_1',
    'test_2',
);
$guzzleRequest = guzzleClient->createRequest(
        $httpMethod,
        $url,
        $headers,
        $body,
        $guzzleRequestOptions
);
$guzzleResponse = $this->guzzleClient->send($guzzleRequest);

我将这个错误的json发送到服务器。

{"0":"test_1","1":"test_2"}

所以,我的问题是我如何使用Guzzle发送JSON BODY列表?

2 个答案:

答案 0 :(得分:0)

尝试使用:

$guzzleRequest = guzzleClient->createRequest(
    $httpMethod,
    $url,
    $headers,
    json_encode($body),
    $guzzleRequestOptions
);

答案 1 :(得分:0)

此代码适用于我通过Guzzle发送json

use GuzzleHttp\Client;
// url destination 
$url = 'http://127.0.0.1:8080';
// headers , if the api dosen't require access token you can remove Authorization from header
$headers = [
    'Accept' => 'application/json',
    'Authorization' => "bearer ".$access_token
];
// body
$body = [
    '1' => 'test1',
    '2' => 'test2'
];
// init Guzzle
$client = new client();
// init Guzzle
$response = $client->post($url , [
    'headers' => $headers, 
    'json' => $body,
]);

$status_code = $response->getStatusCode(); // 200
$status_message = $response->getReasonPhrase(); // ok
相关问题