我正在使用一个非常基本的cURL API。我以前没有真正使用过cURL,所以我正在尽力去理解事物。
为了这个例子,让我们说我可以传递给API的两个值:电子邮件和位置。
此外,我必须使用基本的HTTP身份验证,其中密码为空,用户名是我的API密钥。
为了帮助您了解我的目标,这是API文档中提供给我的示例:
$ curl -X POST https://therequestpath -u $API_KEY: \
--form email=myemailaddress \
--form location='mylocation' \
--form content-type=application/json
{"id":"750ea3d7"}
此时我真的不太明白我在做什么,但这是我到目前为止提出的代码(它没有抛出任何PHP错误,但它没有做我做的事情想要,或者):
$username = 'myapikey';
$password = '';
$host = 'https://therequestpath';
$data = array('email' => 'myemailaddress', 'location' => 'mylocation');
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($process);
curl_close($process);
我不确定我是否在HTTP身份验证失败,传递电子邮件/位置值,或两者兼而有之。任何帮助将不胜感激。
答案 0 :(得分:2)
第一个命令行示例将application / json显示为内容类型,因此您应该在PHP脚本中使用相同的内容:
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
此外,您应该URL-encode每个POST字段,如下所示:
$data = array('email' => urlencode('myemailaddress'), 'location' => urlencode('mylocation'));