【问题标题】:PHP Curl json POST not working for mePHP Curl json POST 不适合我
【发布时间】:2015-08-26 09:34:06
【问题描述】:

您好,我正在尝试使用 PHP 和 Curl 发送 POST 请求。我想发送一个类似这样的JSON

"json":{
  "testString":"test",
  "testInt":1
}

我已经尝试过这段代码来完成这个

curl_init("domain.com");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, '"json":'.$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);

收到请求的我的 laravel 项目没有得到任何信息。

编辑:进一步解释,我的 laravel 项目收到了请求,但没有附加发布数据,没有。

【问题讨论】:

    标签: php json laravel post curl


    【解决方案1】:

    我不确定您为什么在 curl 中使用 CUSTOMREQUEST 选项。 请使用http://curl.haxx.se/libcurl/c/CURLOPT_POST.html

    您也可以在您的 laravel 中通过调用 http://php.net/manual/en/function.http-get-request-body.php 来检查正文

    【讨论】:

      【解决方案2】:

      假设 $data_string:

      $data_string = '"json":{
        "testString":"test",
        "testInt":1
      }';
      

      替换:

      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POSTFIELDS, '"json":'.$data_string);
      

      与:

      curl_setopt($curl, CURLOPT_POST, TRUE);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
      

      【讨论】:

      • 如果 $data_string 是一个数组,你可以在 setopt 中用 json_encode 包装它
      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多