【问题标题】:PHP API getting empty JSON request in POST [duplicate]PHP API在POST中获取空的JSON请求[重复]
【发布时间】:2016-05-30 04:24:22
【问题描述】:

我正在尝试在 php 中开发小型 API 代码,它将使用 PHP curl(从客户端)以 json 格式发送 POST 请求。在接收端(在服务器端)我想解析请求并处理它。但在接收方,它在帖子字段中为我提供了空数组。 下面是我的代码

客户端:

<?php

    $data = array("name" => "Hagrid", "age" => "36");                                                                    
    $data_string = json_encode($data);                                                                                   
    $ch = curl_init($url);                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, "xdata=".$data_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   
    echo $result = curl_exec($ch);

?>

在服务器端:

<?php

    print_r($_POST);

?>

块引用 大批 ( ) 块引用

它总是在服务器端给我空的 POST 数组。 我做错了什么还是有另一种方法来解析请求? 请指导我。

【问题讨论】:

标签: php json api curl


【解决方案1】:

您使用 CURLOPT_HTTPHEADER 标头设置了错误的内容长度。您的整个帖子字符串是strlen("xdata=".$data_string),而您使用的是strlen($data_string)

另外,您使用application/x-www-form-urlencoded 发帖,但将内容类型强行提及为application/json

所以从你的代码中删除下面的块,你应该没问题。

// Remove it
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

【讨论】:

    【解决方案2】:

    您可以使用 php://input 只读流来访问 JSON 发布数据,而不是像这样的 $_POST

    <?php 
        $json = file_get_contents('php://input');
    ?>
    

    它将按原样为您提供 POST 数据。稍后您将能够使用 json_decode() 对其进行解码。

    示例代码 -

    <?php 
       $json = json_decode(file_get_contents('php://input'));
    ?>
    

    【讨论】:

    • 感谢 Vikesh,它现在正在工作。但是无法从 POST 中获取数据?
    • @Shirish, $_POST 是使用 application/x-www-form-urlencoded 或 multipart/form-data 作为 HTTP 时通过 HTTP POST 方法传递给当前脚本的变量的关联数组请求中的内容类型。如需参考,请参阅此链接php.net/manual/en/reserved.variables.post.php
    • 如果我的回答有帮助,请接受。
    • " application/x-www-form-urlencoded" 在我的情况下有效。感谢您的帮助。
    猜你喜欢
    • 2018-11-14
    • 2017-04-09
    • 2019-02-23
    • 1970-01-01
    • 2018-01-09
    • 2019-03-29
    • 1970-01-01
    • 2017-11-26
    • 2017-07-10
    相关资源
    最近更新 更多