Working with a 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'));