2015-07-20 39 views
0

我正在尝试使用需要我同时使用POST和GET的cloudsight API(http://cloudsight.readme.io/v1.0/docs)。我从来没有使用过REST API,但是在做了一些研究后发现,使用PHP进行POST是可行的。
我在api文档中发现了以下代码,但不知道如何将此命令行curl转换为PHP。响应是使用JSON。在php中调用REST cloudsight api

curl -i -X POST \ 
-H "Authorization: CloudSight [key]" \ 
-F "image_request[image][email protected]" \ 
-F "image_request[locale]=en-US" \ 
https://api.cloudsightapi.com/image_requests 


curl -i \ 
-H "Authorization: CloudSight [key]" \ 
https://api.cloudsightapi.com/image_responses/[token] 
+0

的问题应该是“我如何转换此命令行卷曲PHP” – 2015-07-20 00:39:50

回答

0

如果使用PHP curl库,可以为POST做到这一点:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests"); 

$postFields = array(
    'image_request' => array(
     'image' => '@/path/to/image.jpeg', 
     'locale' => 'en-US' 
    ) 
); 

curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: CloudSight [key]')); 

curl_exec($ch); 
curl_close($ch); 

PHP> = 5.5还提供了一个CURLFile类(http://php.net/manual/en/class.curlfile.php)处理文件,而不是传递路径,如上例所示。

对于GET,你可以删除这两条线,并改变网址:

curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); 

另一种选择是使用,如果你在你的项目(http://guzzle.readthedocs.org/en/latest/)使用作曲狂饮。

+0

谢谢你,但我不断收到错误{“错误”:{ “image”:[“can not be blank”]}} – user4348719

+0

我没有API密钥,因此无法直接测试它 - 您是否尝试过使用CURLFile类? – Fraser

1

如果你仍然在回答耐人寻味:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests"); 

$postFields = array(
    'image_request' => array(
     'remote_image_url' => $url, 
     'locale' => 'en-US' 
    ) 
); 

$fields_string = http_build_query($postFields); 

curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: CloudSight [key]', "Content-Type:multipart/form-data")); 

curl_exec($ch); 
curl_close($ch);