【问题标题】:Convert URL encoded to JSON object将编码的 URL 转换为 JSON 对象
【发布时间】: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,并使用我的身份验证(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"}]

所以我知道身份验证正在工作并且数据正确返回,但是现在当我尝试发布我的数据时,我得到:

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

【问题讨论】:

    标签: php json curl


    【解决方案1】:

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

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

    【讨论】:

    • 嗯。有趣的是它可以工作,因为 CURLOPT_POSTFIELDS 不代表有效的 JSON,只是“key=value&key=value&.. etc”。
    【解决方案2】:

    这里有两件事 (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'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2017-10-25
      • 2017-06-16
      • 2023-01-13
      • 2019-07-03
      • 2018-09-20
      • 2017-09-14
      相关资源
      最近更新 更多