如何使用Guzzle创建curl请求

时间:2016-10-22 16:21:32

标签: php curl guzzle

我需要使用guzzle执行以下curl请求:

CURL CALL:
==========
curl -i \
-X POST \
-H "X-Version: 1" \
-H "Content-Type: application/json" \
-H "Authorization: bearer yDqai70hZ8DKD93jy5XtkwPuEf90gU.TUQwZ.ShYjtpy1lkjXvxpbJXViH3ypBIVCAxOyWV" \
-H "Accept: application/json" \
-d '{"text":"Test Message","to":["27999000001"]}' \
-s \
https://api.clickatell.com/rest/message 

我有以下内容:

$client = new \GuzzleHttp\Client();
$result = $client->request('POST', 'https://api.clickatell.com/rest/message', [
    'headers' => [
        'Authorization' => 'Bearer '.config('clickatell.auth_token'),
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'X-Version' => 1
    ],
    'data' => [
        'to' => $sms->to,
        'text' => $sms->content
    ]
]);

但我得到了这样的答复:

[GuzzleHttp\Exception\ClientException]
  Client error: `POST https://api.clickatell.com/rest/message` resulted in a `400 Bad Request` response:
  {"error":{"code":"100","description":"Data malformed","documentation":"http://www.clickatell.com/help/apid
  ocs/error/100. (truncated...)

1 个答案:

答案 0 :(得分:0)

似乎你不对数据进行编码。来自您的回复的错误消息表明请求数据不是有效的JSON。

$requestData = json_encode([
    'to' => $sms->to,
    'text' => $sms->content
]);

$requestHeaders =  [
    'Authorization' => 'Bearer '.config('clickatell.auth_token'),
    'Accept' => 'application/json',
    'Content-Type' => 'application/json',
    'X-Version' => 1
];

$result = $client->request(
    'POST', 
    'https://api.clickatell.com/rest/message', 
    [
       'headers' => $requestHeaders,
       'data' => $requestData
    ]
);

此外,您可以使用post()方法,而不是request()

$result = $client->post(
    'https://api.clickatell.com/rest/message', 
    [
       'headers' => $requestHeaders,
       'data' => $requestData
    ]
);