将编码的URL转换为JSON对象

时间:2014-09-12 08:35:57

标签: php json curl

我之前从未使用过JSON对象,但我认为这可能是我想要实现的最佳途径(如果你认为有更好的选择请告诉我,尽管我不能使用SOAP)< / p>

我正在尝试通过POST向API提交一些数据,以便将一些数据添加到存储为XML的新闻稿列表中。以下是我要完成的请求的文档:https://api.dotmailer.com/v2/help/wadl#PostAddressBookContacts

访问API网址并进行身份验证时,我会看到以下数据:

<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,并使用我的身份验证(apipasswordapiemail用户名)

$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"}]

所以我知道auth工作正常并且数据正确回传,但现在当我尝试发布我的数据时,我得到了:

{"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可读的内容?

2 个答案:

答案 0 :(得分:1)

尝试内容类型application/json,如下所示:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json'));

答案 1 :(得分:0)

这里有两件事(a)缺少内容类型头JSON,(b)有效负载不是JSON。

// setup request to send json via POST.
$payload = json_encode(array("json"=> $data)); // or json_encode(array($data));
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );

// set proper content-type for sending JSON
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
相关问题