2011-04-14 88 views
7

我在使用REST的API發佈json對象時遇到了一些困難。我是使用cURL的新手,但我已經全面搜索,試圖找到我的問題的答案,但總結得不夠。我的cURL請求總是返回false。我知道它甚至沒有發佈我的json對象,因爲我仍然會從url獲得響應。我的代碼如下。cURL PHP RESTful服務總是返回FALSE

<?php 

//API KEY = APIUsername 
//API_CODE = APIPassword 
$API_Key = "some API key"; 
$API_Code = "some API code"; 
$API_email = "[email protected]"; 
$API_password = "ohhello"; 
$url = "http://someURL.com/rest.svc/blah"; 


$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_URL, $url); 
header('Content-type: application/json'); 
$authData = "{\"APIUsername\":\"$API_Key\",\"APIPassword\":\"$API_Code\",\"EmailAddress\":\"$API_email\",\"Password\":\"$API_password\"}"; 
curl_setopt($ch, CURLOPT_POSTFIELDS, $authData); 

//make the request 
$result = curl_exec($ch); 
$response = json_encode($result); 
echo $response; 

curl_close() 
?> 

的$響應返回只是 「假」

有什麼想法?

回答

24

$response很可能是錯誤的,因爲curl_exec()返回false(即失敗)爲$result。 Echo out curl_error($ch)(在curl_exec的調用之後)查看cURL錯誤,如果這是問題。

在另一個筆記上,我認爲您的CURLOPT_POSTFIELDS格式無效。你不會傳遞一個JSON字符串。

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

-- PHP docs for curl_setopt()


更新

的快捷方式,以避免SSL錯誤是添加此選項:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

您獲得SSL驗證錯誤,因爲捲曲,不同的瀏覽器,沒有預先加載的受信任證書頒發機構(CA)列表,因此默認情況下不會信任SSL證書。快速解決方案是僅使用上面的行接受未經驗證的證書。更好的解決方案是手動添加您想接受的證書或CA(s)。有關更多信息,請參閱this article on cURL and SSL

+0

關於curl_error($ ch)我在下面的消息。這是我想要發佈的網址的問題嗎? 「SSL證書問題,請驗證CA證書是否正常。詳細信息: 錯誤:14090086:SSL例程:SSL3_GET_SERVER_CERTIFICATE:證書驗證失敗」 – stekrose 2011-04-14 03:29:25

+1

我認爲這很常見。試試'curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);'。 – Wiseguy 2011-04-14 04:10:35

+0

工作完美。謝謝您的幫助! – stekrose 2011-04-14 04:36:08