Php 在POST请求中设置API密钥时出现问题
试图通过curl发出API请求。API文档说我必须提出如下POST请求:Php 在POST请求中设置API密钥时出现问题,php,curl,http-post,Php,Curl,Http Post,试图通过curl发出API请求。API文档说我必须提出如下POST请求: POST url Headers: Content-Type: “application/json” Body: { Context: { ServiceAccountContext: "[Authorization Token]" }, Request:{ Citations:[ { Volu
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_密钥。我得到的错误是创建了一个SecurityContext对象,我认为这与文章正文中讨论上下文和ServiceAccountContext的部分有关
我查看了cURL文档,没有看到如何设置它。有什么建议吗?非常感谢 问题在于您不正确地使用了CURL选项。根据,当您将
CURLOPT_POSTFIELDS
选项设置为数组
时,CURL强制内容类型
标题设置为多部分/表单数据
。i、 e.设置CURLOPT_HTTPHEADER
选项的行被忽略
您必须通过JSON_encode
函数将$postFields
转换为JSON字符串,然后再将其传递给CURLOPT_postFields
选项:
...
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
...
感谢事后诸葛亮,在阅读你的答案之前,我刚刚开始完全按照你说的做(使用json_编码)。API密钥现在已经被识别,现在我只是修补请求部分以使其工作。感谢您向我确认我在正确的轨道上。@Cbomb如果这个答案能解决您的问题,您可以选择“已接受”