【问题标题】:Content-Type application/json doesn't return POST fieldsContent-Type application/json 不返回 POST 字段
【发布时间】:2018-02-06 18:31:10
【问题描述】:

我正在向我的服务器上的文件发出 cURL 请求并且它正在打印空数组,除非我从请求中删除 Content-Type: application/json 标头。为什么会出现?它应该期望 json 格式作为回报....

$o = [ 'key' => 'value123' ];

        $headers[]  = 'Content-Type: application/json';
        $headers[]  = 'Moj-pierwszy-header: prosty/do/zapamietania';


        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, $path.'test.php');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $o);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch); 
        curl_close($ch);      



        echo( $output );

和test.php

echo json_encode( $_POST );

有人吗?有什么想法吗?

【问题讨论】:

  • 你没有发布 JSON...
  • @AbraCadaver 即使我对发送字符串进行编码,它也不起作用。

标签: php json xml curl header


【解决方案1】:

请参考以下代码sn-p:

     $o = json_encode([ 'key' => 'value123' ]);

     $headers[]  = 'Content-Type: application/json';
     $headers[]  = 'Moj-pierwszy-header: prosty/do/zapamietania';


    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $path.'test.php');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $o);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch); 
    curl_close($ch); 

    echo( $output );

对于输出,使用下面的代码 sn-p 代替 $_POST:

$post = json_decode(file_get_contents('php://input'));

希望对你有用。

【讨论】:

  • 我尝试将 $o 作为编码的 json 发送,但结果仍然是一个空数组。你检查过它是否在服务器上工作吗?
  • 在 test.php 中,尝试 $post = json_decode(file_get_contents('php://input'));接收发布的数据。它会起作用的。
  • 不幸的是,我收到一条消息:可恢复的致命错误:stdClass 类的对象无法在 /opt/lampp/htdocs/ucado3/external-CMS/headers 请求响应 test/test.php 中转换为字符串在第 14 行
  • ok 发现了我的问题,我尝试在 test.php 中回显结果并且它很好,除非你没有尝试回显数组:) 它工作得很好我需要检查这个'php: //input'参数更深入。点赞