繁体   English   中英

使用cURL API

[英]Working with a cURL API

我正在使用一个非常基本的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身份验证失败,传递电子邮件/位置值,或两者兼而有之。 任何帮助,将不胜感激。

第一个命令行示例将application / json显示为内容类型,因此您应该在PHP脚本中使用相同的内容:

curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

您还应对每个POST字段进行URL编码 ,如下所示:

$data = array('email' => urlencode('myemailaddress'), 'location' => urlencode('mylocation'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM