【发布时间】:2018-02-28 07:03:52
【问题描述】:
cURL 对我来说是新的。我正在尝试通过 PHP cURL 集成一个 api。我尝试访问的 api 要求将参数作为键值对发送,而不是 json。他们在文档中的示例 cURL 请求是:
curl -i -X POST -d 'api_key=my_api_key' -d
'email=john@doe.com' -d "first_name=Joe" -d "last_name=Doe" -d
"cust_id=cus_401"
https://serviceurl.com/api/create
我的代码显然正在向他们的 api 发送空参数。
$service_url = 'https://serviceurl.com/api/create';
$curl = curl_init($service_url);
$email = $this->session->userdata('email');
$postArray = array(
'api_key' => 'my_api_key',
'email' => $email,
);
$curl_post_data = $postArray;
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
echo $curl_response;
echo $info;
任何建议将不胜感激。
【问题讨论】:
-
他们的例子比你的代码有更多的字段——你只使用了两个——这可能是原因吗?此外 - POST 方法存在细微差别 -
application/x-www-form-urlencoded或multipart/form-data取决于您是使用简单数组作为 POST 数据还是使用http_build_query创建数据字符串 -
其他字段不是必需的。只是 api 密钥和电子邮件参数。您能否进一步说明 POST 方法的区别。我不太明白。谢谢
-
php.net/manual/en/function.curl-setopt.php ~ 寻找
CURLOPT_POSTFIELDS阅读描述。基本上 -If value is an array, the Content-Type header will be set to multipart/form-data所以这取决于 api 是期待 urlencoded 还是 multipart 数据