使用cURL和PHP进行POST请求


using cURL with PHP for POST request

如果这真的很模糊,很抱歉,我对cURL和与API的交互都是新手。

目前,我已经创建了一个具有所需身份验证详细信息的URL,该URL将访问API(dotmailer),并在地址簿中显示具有给定ID的联系人。

$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';

这让我有点像这样:

https://username:password@api.dotmailer.com/v2/address-books/listID/联系

这是页面中的XML

<ApiContact>
<Id>1058905201</Id>
<Email>email@email.com</Email>
<OptInType>Unknown</OptInType>
<EmailType>Html</EmailType>
<DataFields i:nil="true"/>
<Status>Subscribed</Status>
</ApiContact>
</ArrayOfApiContact>

现在我需要将一个变量POST到API。我的变量是$useremail

我计划使用cURL来实现这一点,因为我使用的是PHP,而不是SOAP,而是REST.

我对此完全陌生,但我尝试了一些不起作用的代码,但嘿,我试过了!

// Authenticate
$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';
// open connection
$ch = curl_init();
// set the URL
curl_setopt($ch,CURLOPT_URL, $auth_url);
curl_setopt($ch,CURLOPT_POST, $useremail);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);

我知道这还有很长的路要走,但是:

  • 这将我从API发送到一个404页面
  • 我知道我在某个地方错过了将其添加到XML上的<email>的操作
  • 文档中引用了我没有提到的方法PostAddressBookContacts(),那么它会去哪里呢

很抱歉,如果这是模糊的。我感谢任何人的建议。

首先,如果您在浏览器中启动此url:

https://username:password@api.dotmailer.com/v2/address-books/listID/contacts

它对你有用吗?

如果是,请回显$auth_url。

$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';
echo $auth_url;

并检查您的url是否构造正确。然后:

编辑

$data = array("Email" => "email@email.com");                                                                    
$data_string = json_encode($data); 
$req = curl_init($auth_url);
curl_setopt($req, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($req, CURLOPT_POST, 1);
curl_setopt($req, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($req, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
); 
$res = curl_exec($req);
curl_close($req);