2015-07-20 40 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);