dragon8837 2011-11-12 15:36
浏览 272
已采纳

使用PHP cURL发送非键值对POST请求?

Working with a RESTful API (for Rackspace's API for domain records) and I have encountered something for the first time. That is, sending an request as a JSON file and not the usual key-value paired data.

In my case, I am supposed to send a string in JSON format, WITHOUT a key corresponding to it. All the examples I have encountered with cURL always assumes the request page expects one. Besides, it seems that the CURLOPT_POSTFIELDS option expects an array (read: key-value pair), anyway.

I am able to set the necessary headers (the Content-Type, and other authentication headers), but I am seriously stuck on putting up the necessary JSON string into the request.

How can I do this?

EDIT:

Here is the API Documentation:

POST https://dns.api.rackspacecloud.com/v1.0/1234/domains/2725233/records
Accept: application/json
X-Auth-Token: ea85e6ac-baff-4a6c-bf43-848020ea3812
Content-Type: application/json
Content-Length: 725

{
  "records" : [ {
    "name" : "ftp.example.com",
"type" : "A",
"data" : "192.0.2.8",
"ttl" : 5771
  }, {
"name" : "example.com",
"type" : "A",
"data" : "192.0.2.17",
"ttl" : 86400
  }, {
"name" : "example.com",
"type" : "NS",
"data" : "dns1.stabletransit.com",
"ttl" : 3600
  }, {
"name" : "example.com",
"type" : "NS",
"data" : "dns2.stabletransit.com",
"ttl" : 3600
  }, {
"name" : "example.com",
"priority" : 5,
"type" : "MX",
"data" : "mail.example.com",
"ttl" : 3600
  }, {
"name" : "www.example.com",
"type" : "CNAME",
"comment" : "This is a comment on the CNAME record",
"data" : "example.com",
"ttl" : 5400
  } ]
}
  • 写回答

3条回答 默认 最新

  • doufei1852 2011-11-12 16:39
    关注

    Assuming you are POSTing a file:

    $fh = fopen('/path/to/file', 'r');
    $ch = curl_init($url);
    curl_setopt_array($ch, array(
      CURLOPT_INFILE => $fh,
      CURLOPT_POST => TRUE,
      //...any other options you might need
    ));
    curl_exec($ch);
    curl_close($ch);
    

    If POSTing data (like json) use CURLOPT_POSTFIELDS

    $data = '{ "foo": "bar" }';
    curl_setopt_array($ch, array(
      CURLOPT_POSTFIELDS => $data,
      CURLOPT_POST => TRUE,
      //...any other options you might need
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题