2014-10-07 359 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