2014-10-07 358 views
0

試圖通過curl發出API請求。該API文檔說我必須按如下方式進行POST請求:在POST請求中設置API密鑰時遇到問題

POST url 
Headers: 
    Content-Type: 「application/json」 
Body: 
{ 
    Context: { 
     ServiceAccountContext: "[Authorization Token]" 
    }, 
    Request:{ 
      Citations:[ 
      { 
       Volume: int, 
       Reporter: str, 
       Page: int 
      } 
      ] 
    } 
} 

這裏是我的捲曲要求:

$postFields = array(
      'Volume' => int, 
      'Reporter' => str, 
      'Page' => int, 
      'ServiceAccountContext' => $API_KEY 
); 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);  
curl_setopt($ch, CURLOPT_HEADER, false);  
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json")); 
curl_setopt($ch, CURLOPT_POST, count($postFields));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);   

$output=curl_exec($ch); 

但API是不承認,我已經通過POST現場提交的API_KEY。我回來的錯誤是創建一個SecurityContext對象,我認爲這是與關於Context和ServiceAccountContext的POST正文部分有關的。

我已經查看了cURL文檔,並沒有看到我可以如何設置它。有什麼建議麼?謝謝一堆。

回答

1

問題是您使用CURL選項不當。根據manual,當您將CURLOPT_POSTFIELDS選項設置爲array時,CURL強制Content-Type標頭爲multipart/form-data。即您設置CURLOPT_HTTPHEADER選項的行被忽略。

你必須將它傳遞給CURLOPT_POSTFIELDS選項之前$postFieldsjson_encode功能轉換成JSON字符串:

... 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json")); 
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));   
... 
+0

感謝天誅地滅,我剛開始讀你的答案之前,你說什麼(使用json_encode)。 API密鑰現在正在被識別,現在我只是修改請求部分來完成這項工作。感謝您向我確認我正走在正確的軌道上。 – Cbomb 2014-10-07 23:03:10

+0

@Cbomb如果它解決了你的問題,你可以選擇這個答案爲「接受」 – hindmost 2014-10-08 07:53:04