我正在尝试将带有JSON数据的POST请求提交到api端点。端点需要一个传递api凭据的查询字符串,而且还需要发布JSON数据。
[当我尝试使用PHP cURL进行此操作时,如下所示,显然已删除了查询字符串-因此,由于缺少api键,api拒绝了该请求。
[在测试对api端点的访问权限时,我可以使用Postman轻松完成此操作。
如何使cURL请求包含both查询字符串和JSON POST主体?
示例代码:
// $data is previously defined as an array of parameters and values.
$url = "https://api.endpoint.url?api_key=1234567890";
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
您做得差不多了。
有时您需要放松SSL验证。否则,更新php ca bundle:https://docs.bolt.cm/3.7/howto/curl-ca-certificates
添加以下内容:
$headers = array(
"Content-type: application/json;charset=UTF-8",
"Accept-Encoding: gzip,deflate",
"Content-length: ".strlen($json),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
有时您也需要更改编码:
$result = utf8_decode($result);
并检查返回的数据。