【发布时间】:2014-09-12 08:35:57
【问题描述】:
我以前从未使用过 JSON 对象,但我认为这可能是我想要实现的最佳途径(如果您认为有更好的选择,请告诉我,尽管我不能使用 SOAP)
我正在尝试通过 POST 向 API 提交一些数据,以便将一些数据添加到存储为 XML 的时事通讯列表中。这是我要完成的请求的文档:https://api.dotmailer.com/v2/help/wadl#PostAddressBookContacts
访问 API url 并进行身份验证时,我看到以下数据:
<ArrayOfApiContact xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://apiconnector.com">
<ApiContact>
<Id>1058905201</Id>
<Email>email@email.co.uk</Email>
<OptInType>Unknown</OptInType>
<EmailType>Html</EmailType>
<DataFields i:nil="true"/>
<Status>Subscribed</Status>
</ApiContact>
</ArrayOfApiContact>
所以我尝试使用变量而不是硬编码的电子邮件进行复制:
$xml = array(
'id' => urlencode('123456789'),
'email' => urlencode($useremail),
'optInType' => urlencode('Unknown'),
'emailType' => urlencode('Html'),
'dataFields' => urlencode(':null'),
'status' => urlencode('Subscribed')
);
我在这里合并数组:
foreach($xml as $key=>$value) { $xml_string .= $key.'='.$value.'&'; }
然后使用 cURL 将请求发布到 API,并使用我的身份验证(apipassword 和 apiemail 哪个用户名)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$auth_url);
curl_setopt($ch,CURLOPT_POST, count($xml));
curl_setopt($ch,CURLOPT_POSTFIELDS, $xml_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$apiemail:$apipassword");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$result = curl_exec ($ch);
curl_close ($ch);
我已经在没有 POST 的情况下对此进行了测试,并且确实以这种形式获取了数据:
[{"id":1058905201,"email":"email@email.co.uk","optInType":"Unknown","emailType":"Html","dataFields":null,"status":"Subscribed"}]
所以我知道身份验证正在工作并且数据正确返回,但是现在当我尝试发布我的数据时,我得到:
{"message":"Content type \"application/x-www-form-urlencoded\" is not supported. Please use one of: application/json,application/xml ERROR_CONTENT_TYPE_IS_NOT_SUPPORTED"}
那么如何将我的 URL 编码数组转换为 API 可读的内容?
【问题讨论】: