如何使用 POST 在 CURL 请求中传递 JSON

How to pass JSON in CURL request using POST

我有一个 JSON 字符串,我想使用 POST 传递给 API。

当我尝试传递数据时,我得到 "JSON not valid"。我已经使用 API 的内置测试工具手动测试了 JSON 字符串,并且知道该字符串有效。该函数适用于使用 GET 从 API 获取。

我怀疑使用 POST 时 PHP/curl 语法可能有误?

function curl($url = null,$method = null,$body = null){

    $loginauth =  base64_encode('SECRETKEY');

    if($method == null){

        $method = 'GET';
        $headers = array(
            'Accept: application/hal+json,application/vnd.error+json',
            'Authorization: Basic '.$loginauth
        );

    }else{

        $method = 'POST';
        $headers = array(
            'Content-Type: application/json',
            'Authorization: Basic '.$loginauth
        );
    }

    if($url == null){
        $url = 'https://coolapi.com/api/v1/companies';
    }

    if($body == null){
        $body = '';
    }

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $url,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $body
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if($err){
        return $err;
    }else{
        return json_decode($response);
    }
}

我调用的函数:

$url = 'https://one-url';
$data = '{
  "date": "2017-02-22",
  "identifier": "1337",
  "lines": [
    {
      "test": "this is a test",
    }
  ],
  "name": "Wolf"
}';


$register_sale = curl(
    $url,
    'POST',
    $data
);

在PHP中,如果在数据中传递json,则没有预定义数据类型为json; PHP 会将其视为字符串。因此,声明数组并使用 json_encode 转换为 json,它将起作用。

试一试。

$data = [
  "date"=> "2017-02-22",
  "identifier" => "1337",
  "lines" => [  "test" => "this is a test" ],
  "name"=> "Wolf"
];
$json = json_encode($data);

$register_sale = curl($url,'POST', $json);

参考:https://lornajane.net/posts/2011/posting-json-data-with-php-curl