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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3