我正在与Shutter Stock API交谈。我确定问题不是SS而是更多我的PHP Curl帖子的格式化,好像我通过终端发送此请求我得到了正确的答复。
终端卷曲命令如下:
curl "https://api.shutterstock.com/v2/images/licenses?subscription_id=$SUBSCRIPTION_ID" \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "Content-Type: application/json" \
-X POST \
--data '{
"images": [
{ "image_id": "137111171" }
]
}
所以我正在玩这个作为PHP curl发送,而这就是我所拥有的:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = new Object();
$params = {
'images' : {'image_id' : '137111171'}
};
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($params));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
/*$json = json_decode($response, true);
if (json_last_error()) {
echo '<span style="font-weight:bold;color:red;">Error: ' . $response . '</span>';
} else {*/
return $response;
Shutter Stock的响应表单是“Decode body failure”,这是一个自定义错误响应。我认为问题在于$ params变量以及它是如何格式化的。问题是这是一个帖子,我怀疑在另一方面SS是以特定的方式解码它。正确的curl参数在上面的bash卷曲中为:
--data '{
"images": [
{ "image_id": "137111171" }
]
有没有人对如何正确格式化这个特定的--data值有任何建议,以便我可以将其作为POST发送?
由于
答案 0 :(得分:0)
我认为您传递了错误的CURLOPT_POSTFIELDS
数据。尝试:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = [
'images' => ['image_id' => '137111171']
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;
答案 1 :(得分:0)
你的PHP代码包含无效的语法,PHP也没有名为Object
的类,但你可能正在寻找StdObject
,但即便如此,这里没有多大意义..也是你'不要urlencoding $ SUBSCRIPTION_ID。删除无效的语法部分,并使用json_encode,而不是json_decode ..
curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( array (
'images' => array (
array (
'image_id' => '137111171'
)
)
), JSON_OBJECT_AS_ARRAY ) );
(编辑,通过评论,api要求适用的数据是一个数组而不是一个对象,因此我添加了JSON_OBJECT_AS_ARRAY标志。)