通过 cURL POST PHP 传递 JSON


Passing JSON through cURL POST PHP

我一直在尝试使用 cURL 通过我的 Web 应用程序传递 JSON - 我现在有点卡住了。

这是我尝试过的:

第 1 步:

我尝试使用此发布 JSON

<?php 
  public function post(){
    $cars = array("Volvo", "BMW", "Toyota");
    $json = json_encode($cars);
    $ch = curl_init("http://localhost/api_v2/url?key=***");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $json));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
  }
?>

第 2 步:

我试图使用这个接收 JSON

public function get(){
        $json = json_decode(Input::get('json'));
        dd($json); // null
    }

结果: - 当我做dd($json);时,我一直得到空

有人可以帮我指出我做错了什么吗?


细节:

  • 我使用PHP框架:Laravel 4.0
  • 我很肯定 URL 参数是正确的,因为我可以去它
  • 我也确定 JSON 没有损坏,因为在添加print("<h1> JSON </h1><pre>".print_r($json,true)."</pre><br><hr><br>");后我可以看到我的 JSON 显示正常。

  • 见图片

就调试工作而言,您应该转储响应,而不是json_decode尝试解析它。

所以改变这个

public function get() {
    $json = json_decode(Input::get('json'));
    dd($json); // null
}

对此

public function get() {
    dd(Input::get('json'));
}

应该更好地帮助您跟踪真正的问题,这很可能是服务器没有使用有效的 JSON 进行响应。

另一种选择是使用 json_last_error 来查看响应无法解析的原因。

public function get() {
    $json = json_decode(Input::get('json'));
    // If the response was parseable, return it
    if($json !== null)
        return $json;
    // Determine if the response was a valid null or
    // why it was unparseable
    switch (json_last_error()) {
        // The server could respond with a valid null,
        // so go ahead and return it.
        case JSON_ERROR_NONE:
            return $json;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
            break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
            break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
            break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        default:
            echo ' - Unknown error';
            break;
        }
}

看起来您没有返回 cURL 调用的结果。

public function post()
{
   // The first part of your original function is fine...
   $response = curl_exec($ch);
   curl_close($ch);
   // But you need to return the response!
   return $response;
}

如果您的客户端是脚本(即:不是浏览器),则无法在服务器端打印内容。

您在服务器端打印的所有内容都将返回到客户端(post() 脚本)。

话虽如此,您的 json 应该存在于 $response 变量中。你可以输出它。但这不是调试 api 请求的最佳方式。

更简单的方法是删除 dd() 并改为写入日志文件。