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

时间:2017-02-22 12:33:09

标签: php php-curl

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

当我尝试传递数据时,我得到“JSON无效”。我已经使用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
);

1 个答案:

答案 0 :(得分:1)

在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